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,john@domain1.com
Frank,frank@domain2.com
Julie,julie@domain3.com
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
$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.
<?php
//Name,Email
//John,john@domain1.com
//Frank,frank@domain2.com
//Julie,julie@domain3.com
// 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 : john@domain1.com
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With