Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP CSV VLookup

I'm looking a PHP function that can read a CSV file and perform a vlookup on column 1 to echo the relating value on the same row in column 2.

For example, if the CSV contains:

Name,Email
John,[email protected]
Frank,[email protected]
Julie,[email protected]

I would like to lookup against a Name and echo the email value.

Something like:

<?php
$name = "Name to be inserted";
$csv = 'filename.csv';

*function to vlookup $name in $csv, get column 2 value and pipe to $email* 

echo $email;
?>

Can anyone suggest a function that can accomplish the above?

Thank you

like image 998
MrGoodBytes Avatar asked May 28 '15 06:05

MrGoodBytes


2 Answers

$csv = array_map('str_getcsv', file('test.csv'));
$findName="Frank";
foreach($csv as $values)
{
  if($values[0]==$findName)   // index 0 contains the name
    echo $values[1];          // index 1 contains the email  
}

Please note that the indexes used in this answer are specific to the csv format you gave. You will have to adjust the indexes if format changes.

like image 166
Hanky Panky Avatar answered Sep 28 '22 03:09

Hanky Panky


<?php

//Name,Email
//John,[email protected]
//Frank,[email protected]
//Julie,[email protected]

// Function Definition
function getEmailFromCSV($csv_name, $name) {
$file = fopen($csv_name, "r");

while (!feof($file)) {
    $arr = fgetcsv($file);
    if ($arr[0] == $name) {
        echo $arr[1];
    }
}
fclose($file);
}

// Function Calling
getEmailFromCSV('abc.csv', 'John');

// Input : John
// Output : [email protected]

?>
like image 34
Priyranjan Singh Avatar answered Sep 28 '22 03:09

Priyranjan Singh