65

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

Musa
  • 3,944
  • 4
  • 21
  • 27
  • You should answer your own question here so you can close the question. – Jim Rubenstein Aug 01 '12 at 15:57
  • 4
    For future reference this has to be done BEFORE the call to `fopen`. I added it between the call to `fopen` and the call to `fgetcsv` for testing and it didn't work. I'll never see that twenty minutes every again. :-) – Scott Keck-Warren Aug 02 '12 at 17:53
  • @ScottWarren - I cannot believe I have not read this until now. For the past YEAR I could not figure out why my CSV import in Store Locator Plus was not working on osx files! Thanks for sharing! – Lance Cleveland Sep 04 '13 at 00:51
  • This should default to '1' in PHP instead of us trying to figure this out. – Ron May 02 '14 at 17:48

2 Answers2

37

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.

phihag
  • 278,196
  • 72
  • 453
  • 469
  • 6
    My client gave me a file which contains \r. I asked him which OS version he uses, he told he uses leopard and office 2008. I am building a plugin for them where there will have many end user, so i'm trying to build this cross platform. – Musa Dec 27 '10 at 21:57
  • 1
    In my case, the user was on Mac OS (10.9, Maverick) using MS Office Excel 2011. – marcovtwout Dec 30 '13 at 14:14
  • In my case it was Excel 2013 on Windows 7. – JaseC Mar 26 '14 at 00:55
  • 1
    Now it's 2016 and I still get people uploading this kind of files, generated by current Excel on Mac OS. – Phil May 09 '16 at 02:27
  • 1
    It's 2018 now - _Still_ getting garbage CSV files from clients with unpredictable line endings; `auto_detect_line_endings` is pure magic! – quickshiftin Feb 01 '18 at 16:14
5

\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);

Andrey Vorobyev
  • 896
  • 1
  • 10
  • 37
spekary
  • 408
  • 5
  • 10