Search code examples
phpcsvimportfgetcsv

str_getcsv() file returns all rows in one long array, and fgetcsv() returns only the top header row


I have a file that I saved as a CSV file using Excel (I tried from both Windows 7 and Mac OSX to avoid any compatibility issues).

When I do this:

ini_set('auto_detect_line_endings', true);
$filename = 'import/clientsimport.csv';
$csvfile = file_get_contents($filename);
$csvarray = str_getcsv($csvfile);
print_r($csvarray);
mysql_close();

All the rows turn inte one row, and I get an array that is only 1 level deep and runs on and on to the thousands in keys.

So I tried an alternative approach:

ini_set('auto_detect_line_endings', true);
$filename = 'import/clientsimport.csv';
$csvfile = fopen($filename,'r');
$csvarray = fgetcsv($csvfile);
print_r($csvarray);

This ONLY returns the 1st row (row of headers) and doesn't go beyond it. How do I do this properly? There are hundreds of rows, and about a dozen arrays per row, so I should be getting a 2 dimensional one.

In the CSV, each row is broken by a linebreak, and values separated by commas - no enclosures.


Solution

  • Solved the question by another search with different keywords:

    php str_getcsv array issue

    Has the answer. Basically I modified my file reading mechanism to:

    $csvfile = fopen($filename,'rb');
    while(!feof($csvfile)) {
    $csvarray[] = fgetcsv($csvfile);
    }
    

    rb I assume is reading with linebreaks? And the while statement loops through the rows. I totally forgot how the fopen works in terms of breaking the content apart and having to loop through, unlike file_get_contents() which returns one long string only.