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.

1

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please elaborate on your answer?
Fantastic, thank you very much for this. You are totally correct!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.