Looping through a csv with fgetcsv

user3725781 picture user3725781 · Nov 11, 2014 · Viewed 30.1k times · Source

I have a csv file with 3 columns: email address, first name and last name. I have got the stage where I can print out the array using the following code:

<?php
$file = fopen("testEmails.csv","r");

while(! feof($file))
{
print_r(fgetcsv($file));
}

fclose($file);
?>

This prints the array, so every field in a row. What I want it to print is purely the values in the first column of the row. How would this be done, documentation on fgetcsv seems very sketchy to me (a relative beginner).

Thanks.

Answer

Cody Caughlan picture Cody Caughlan · Nov 11, 2014

The first example in the fgetcsv() documentation contains the nuggets of what you need.

$file = fopen("testEmails.csv","r");

while (($data = fgetcsv($file)) !== FALSE)
{
    echo "email address " . $data[0];
}

fgetcsv() returns a numerically indexed array of representing the columns, so you just want to print the first column.