Fgetcsv prints all data to the first line

Using fgetcsv was an option I found for reading the csv files the system requires. But it seems like it doesn't work every time (in fact, it is very rare when this code works).

if (($handle = fopen($file, 'r')) !== FALSE) {
    set_time_limit(0); // necessary if a large csv file

    $row = 0;
    while (($data = fgetcsv($handle, 0, ',')) !== FALSE) {
        print_r($data);
        // .. here I do some stuff with the data
        // .. The result should be an array with 5 columns and it run multiple times (for the amount of lines in the file)
        // .. The result however is one array with a over 9000 columns (really over 9000, it 9489 in the file that I'm testing)
    }
    fclose($handle);
    die();
}

      

I tried to check the end of the line by calling this before the code, without much success.

ini_set('auto_detect_line_endings', true);

      

The file is exported by another program by the client and I cannot "update" it to meet the needs of the software. Is there a way to deal with this encoding

/ line-ending

on csv?

+3


source to share


1 answer


From PHP Manual (radical idea I know)

length parameter

Must be greater than the longest line (in characters) to be found in the CSV file (including end-of-line characters). It became optional in PHP 5. By omitting this parameter (or setting it to 0 in PHP 5.1.0 and later), the maximum string length is not limited, which is a little slower.

I don't know which PHP version you are using, but try setting the parameter to something sane and you should start getting one line at a time.



For example,

while (($data = fgetcsv($handle, 4096, ',')) !== FALSE) {

      

0


source







All Articles