Value Search with PHP – Is it Possible?

Question:

Is it possible to access a .CSV file, capture a value and look it up in another .CSV file?!

Example:
Note: The images below are from .xlsb files, but it's just for demonstration, I'm using .csv files

The code should in this case store a value and look for it in another .CSV file, in my case, it would be the same as these images:

https://prnt.sc/goaudl
https://prnt.sc/goau8y

It will look for the value "80283022" in the worksheet "works", save it and look for it in the worksheet "items" and when it finds it (in line 155) it will get the value from column G which is "6".

It's possible?!

I have a little code that accesses the .csv files and collects some data.

<?php
$file1 = __DIR__ . '/download/Trabalhos.csv';
$csv1 = file($file1);
foreach ($csv1 as $row1 => $line1) {
    $row1++;
    $column1 = str_getcsv($line1, ';');
    if ($row1 == 2) {
        $column1[6]."<br>";
        $valor1 = $column1[6];
    }
}
?>

Answer:

I did this function, you enter the file you want to search, the column where you will search for the value and the column where the search value and value will be returned.

<?php
function pesquisaCsv($arquivo, $coluna_pesquisa, $coluna_resultado, $valor){
    if (($handle = fopen($arquivo, "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if($data[$coluna_pesquisa] == $valor){
                return $data[$coluna_pesquisa];
            }
        }
        fclose($handle);
    }
}

$file1 = __DIR__ . '/download/Trabalhos.csv';
$csv1 = file($file1);
foreach ($csv1 as $row1 => $line1) {
    $row1++;
    $column1 = str_getcsv($line1, ';');
    if ($row1 == 2) {
        $column1[6]."<br>";
        $valor1 = $column1[6];
        pesquisaCsv('/download/outro_arquivo.csv', 0, 6, $valor1)
    }
}
?>
Scroll to Top
AllEscort