PHP CSV VLookup

I am looking for a PHP function that can read a CSV file and do vlookup in column 1 to reflect the related value in 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 search for the name and echo value of the email.

Sort of:

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

thanks

+5
source share
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 specified. If you change the format, you will have to adjust the indices.

+4
source
 <?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 ?> 
+2
source

All Articles