Searching for values with PHP - Is it possible?

Asked

Viewed 118 times

3

It is possible to access a file . CSV, capture a value and search it in another file . CSV?!

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

The code should in case store a value and search in another file . CSV, in my case, would be equal to 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 you find it (on line 155) you will get the value of column G which is "6".

It is possible?!

I have a small code that accesses the files . csv 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];
    }
}
?>
  • Hello Alex, please do not use "Code snippet" (Stack Snippets) with PHP, read: http://pt.meta.stackoverflow.com/q/2115/3635

  • Sorry! It will not happen again William, thanks for the tip.

1 answer

1


I made this function you enter with the file you want to search, the column where you will search the value and the column where you will return the value and the search value.

<?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)
    }
}
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.