RSS Feed

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!

Posted in PHP on the 26th February 2010

2 people have spoken their minds!

  1. Owltech says:

    I have been uploading a Mac file to a Linux server and had problems with lots of records reading as one one big one. The ini_set above fixed my problem with fopen. Thanks.

  2. bowman says:

    thanks a lot you saved my life

SPEAK YOUR MIND...

Your email address will not be published. Required fields are marked *

*