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.
The fgetcsv() function parses a line from an open file, checking for CSV fields.
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); ?>
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With