Reading a file line by line in reverse with PHP
Here is a handy function for reading a file line by line in reverse (from the end of the file).
function rfgets($handle) {
$line = null;
$n = 0;
if ($handle) {
$line = '';
$started = false;
$gotline = false;
while (!$gotline) {
if (ftell($handle) == 0) {
fseek($handle, -1, SEEK_END);
} else {
fseek($handle, -2, SEEK_CUR);
}
$readres = ($char = fgetc($handle));
if (false === $readres) {
$gotline = true;
} elseif ($char == "\n" || $char == "\r") {
if ($started)
$gotline = true;
else
$started = true;
} elseif ($started) {
$line .= $char;
}
}
}
fseek($handle, 1, SEEK_CUR);
return strrev($line);
}
$filename = 'top-1m.csv';
echo "Reverse reading $filename" . PHP_EOL;
$handle = @fopen($filename, 'r');
for ($i = 0; $i < 10; $i++) {
$buffer = rfgets($handle);
echo $buffer . PHP_EOL;
}
fclose($handle);
The output produced (from the Alexa top 1 million domains list) is:
Reverse reading top-1m.csv
1000000,hingemarketing.com
999999,deluxecar.hu
999998,phototests.com
999997,slutwifegallery.com
999996,himawarigumi.net
999995,niel3d.com
999994,n2itall.blogspot.com
999993,solo-iphone.com
999992,adultmaven.com
999991,celoteh.web.id