Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV imports; all values is one row

Tags:

php

csv

I'm having a problem using a CSV file uploaded via a PHP form. Here is the code:

$row = 1;
if (($handle = fopen($_FILES['csv']['tmp_name'], "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

The only problem is, when I'm interrogating the variable $data it appears the contents of the CSV file is written to one row, rather than multiple rows. As a result, I get an array of 228 column values.

Why is this? Is my PHP script not detecting a new line correctly? If so, is there an option to fix this behaviour?

like image 834
Martin Bean Avatar asked Mar 18 '11 20:03

Martin Bean


People also ask

How do I import data from a CSV file into Excel?

Open Excel 2. Go to 'Data' tab 3. Select 'From Text' (third option from left) and select the .CSV file you want to import. 4. Click 'Next' on the pop-up window. Make sure you select 'Comma' in the next window. You should see your data applied into columns below already. You can add any other information if you need to here.

Why is my CSV file not importing data?

One of the most common CSV import errors is that the file is simply too large. That can be caused by too many fields or records in the file, too many columns, or too many rows. The import error can be caused by limits set by the program using the file or the amount of available memory on the system.

How do I import a CSV file with a comma?

To make the columns be imported successfully, you may need to replace the slash “\” with “,” and save the text file as a .csv file as a workaround. When importing it , select Comma.

Why is all the data shown in one column in Excel?

If, when opening your export in MS Excel, all the data is shown in one column, it's not a problem with the exported data; the data is getting exported as a .CSV file properly, but not picking up the delimiters (commas) correctly when you open it in Excel. To correct this behavior follow one of the solutions below:


2 Answers

set the auto_detect_line_endings ini setting to true:

ini_set('auto_detect_line_endings', true);
like image 111
ChrisR Avatar answered Sep 21 '22 22:09

ChrisR


Most likely problem is the line endings in your source data. Could you make a test CSV file with several columns and rows to confirm or eliminate the data you're testing with?

See also: http://www.php.net/manual/en/filesystem.configuration.php#ini.auto-detect-line-endings

like image 38
Craig A Rodway Avatar answered Sep 21 '22 22:09

Craig A Rodway