Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgetcsv fails to read line ending in mac formatted csv file, any better solution?

Tags:

php

fgetcsv

I was parsing a csv file using php with fgetcsv function. It parsed all content in a line, later i found, csv contains carraige return as "\r". I saw - it was reported as php bug before. I've solved this by setting php runtime configuration which is -

ini_set("auto_detect_line_endings", "1");

is there any more solution or is this the right way?

Thanks

like image 399
Musa Avatar asked Dec 27 '10 20:12

Musa


2 Answers

Setting auto_detect_line_endings is explicitly recommended by the php documentation.

However, I cannot fathom why you would want to delimit lines with \r in 2010. If possible, convert them to the UNIX-style \n.

like image 145
phihag Avatar answered Nov 18 '22 07:11

phihag


\r line endings are created by Microsoft Excel when saving as a CSV file, so there is not much getting around that if you are starting with an Excel spreadsheet.

Using auto_detect_line_endings works fine, or you can normalize line endings with preg_replace("/\r\n|\n\r|\n|\r/", "\n", $subject);

like image 5
spekary Avatar answered Nov 18 '22 06:11

spekary