PHP read in specific csv file column as an array

Josh Pullin picture Josh Pullin · Aug 17, 2012 · Viewed 17.7k times · Source

I am new to PHP and would like to be able to read in a csv file which has two columns, one is the number (kind of like a ID) then the other holds a integer value. I have looked up the fgetcsv function but I have not been able to find a way to read a specific column from the csv file.

I would like to get all the values from the second column only, without the heading.

Any way of doing this?

This is what I have so far:

$file = fopen('data.csv', 'r');
$line = fgetcsv($file);

And this is some sample data from the csv file:

ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00

Any help would be appreciated.

Thanks.

Answer

Marc B picture Marc B · Aug 17, 2012

fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:

$data = array();
while($row = fgetcsv($file)) {
   $data[] = $row;
}

The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:

   $data[] = $row[1];

However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:

   $data[$row[0]] = $row[1];

and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.