php fgetcsv returning all lines

Chris Muench picture Chris Muench · Apr 4, 2011 · Viewed 26.6k times · Source

I have the following csv file:

upc/ean/isbn,item name,category,supplier id,cost price,unit price,tax 1 name,tax 1 percent,tax 2 name,tax 2 percent,quantity,reorder level,description,allow alt. description,item has serial number
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,
,Apple iMac,Computers,,10,12,8,8,10,10,10,1,Best computer,,

When I do this:

if (($handle = fopen($_FILES['file_path']['tmp_name'], "r")) !== FALSE) 
{
    $data = fgetcsv($handle);
    var_dump($data);
}

I get an array with 183 elements, I would expect to only get one line of the csv, but I get the whole file.

I even tried $data = fgetcsv($handle, 1000); and I got the same result

Answer

mholzmann picture mholzmann · Apr 4, 2011

This is most likely a line ending issue. Try enabling auto_detect_line_endings which will attempt to determine the file's line endings.

ini_set('auto_detect_line_endings', true);

If that doesn't resolve the issue, then detect the type of line terminators using the file command:

$ file example.csv
example.csv: ASCII text, with CR line terminators

You can then convert the line endings. I am not sure what OS you are using but there are a lot of utilities out there for file format conversion, e.g. dos2unix.