Reading files with PHP: “auto detect line endings”

With this PHP code:

<?php
$fp = @fopen("file.txt", "r");
if ($fp)
{
	$i = 1;
	while (($line = fgets($fp, 4096)) !== false)
	{
		echo "Line ".$i.": ".$line;
		$i++;
	}
}
?>

And this file.txt content:

aaaaa
bbbbb
ccccc
ddddd

You expect an output like:

Line 1: aaaaa
Line 2: bbbbb
Line 3: ccccc
Line 4: ddddd

A problem appears when you read a file created in a Mac environment (eg, \r instead of \n ). Then you could get something like:

Line 1: aaaaa bbbbb
Line 2: ccccc
Line 3: ddddd

To avoid that and always get a correct (and an expected!) performance, just add this line in the beginning of your code:

ini_set("auto_detect_line_endings", true);

Leave a Reply

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