Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse CSV file which contains a new line to php array

Tags:

arrays

php

csv

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.

like image 653
Henrik Petterson Avatar asked May 26 '17 12:05

Henrik Petterson


People also ask

What does Fgetcsv do in PHP?

The fgetcsv() function parses a line from an open file, checking for CSV fields.

How read a specific column in a CSV file in PHP?

php //this is column C $col = 2; // open file $file = fopen("example. csv","r"); while(! feof($file)) { echo fgetcsv($file)[$col]; } // close connection fclose($file); ?>


1 Answers

$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.

like image 69
Flosculus Avatar answered Oct 13 '22 03:10

Flosculus