Wednesday, October 28, 2015

PHP: fgetcsv(), fgets() and file() line ending detection issues

Having problems with fgetcsv(), fgets() or file() incorrectly detecting line endings? Not a problem!
Depending on the operating system in which the file was created the line endings tend to be different:
Linux: \n
OS X: \n
Windows: \r\n
The best way to get around this is have PHP detect the line ending for you before opening a file. To do this use ini_set(); to tell PHP to detect the line endings:
ini_set('auto_detect_line_endings', true);
You will want to place this before the opening of any files:
ini_set('auto_detect_line_endings', true);
$fhandle = fopen($file, 'r');
And that’s it!
http://v1.srcnix.com/2010/02/26/php-fgetcsv-fgets-and-file-line-ending-detection-issues/