12

I have a CSV file with:

Test1,One line
Test2,"Two lines

Hello"
Test3,One line

As you can see, one of the columns has a value which is separated with a new line.

To parse this CSV file into an array, I run:

$csvArray = array();
$csvData = file_get_contents('file.csv');
$lines = explode(PHP_EOL, $csvData);
foreach ($lines as $line) {
    $csvArray[] = str_getcsv($line);
}
// print_r($csvArray);

It works beside one problem. It reads the new line in the value as a new row, which is completely incorrect.

How do I make it so that it properly reads a multi-line value?

Edit: this question focuses on new lines.

Henrik Petterson
  • 6,862
  • 20
  • 71
  • 155
  • Possible duplicate of [How to parse a CSV file using PHP](https://stackoverflow.com/questions/9139202/how-to-parse-a-csv-file-using-php) – k0pernikus May 26 '17 at 12:44

1 Answers1

15
$fp = fopen('filecsv', 'r');

$csvArray = array();

while ($row = fgetcsv($fp)) {
    $csvArray[] = $row;
}

fclose($fp);

Using explode(PHP_EOL, $csvData) will not correctly split the CSV by its row delimitor. The multi line cell is encapsulated with quotations meaning the row will continue onto new lines until they are closed.

PHP's built in fgetcsv function will correctly read a single row from a file, moving the pointer to the next row in the process. While str_getcsv will only read a single row from a string without considering additional rows (because its a string, not a stream).

Since you have already split the string with explode, your CSV row is broken, so the row will be incomplete.

k0pernikus
  • 60,309
  • 67
  • 216
  • 347
Flosculus
  • 6,880
  • 3
  • 18
  • 42