Reading a file in reverse with PHP
December 19th, 2006 by Ray in PHP/MySQL | Tags: functions, php | Comments OffEver need to read a file from the end of file (EOF) to the start of file (SOF)? Why would you want to do that? Well one example would be to read a log file. You might want to parse the newest entries first and iterate over the older logs later, or not at all.
For those of you familiar with PHP’s array functions, your first through might be to just iterate over the log file and throw each line into an array, then use PHP’s array_reverse() function to take the last lines and put them first in the array. See below:
$file = 'myFile.txt';
$file_contents = array_reverse(file($file));
foreach($file_contents as $line){
echo $line;
}
Now, this is the easiest way to solve the problem but array_reverse() is a costly function to use. However, there are always multiple ways to solve programming problems and I am presenting the solution that I use currently.
Before I jump into the actual code let me explain how it works. Instead of relying on PHP’s array_reverse(), what we will do is seek to EOF and read back 1 character (byte) at a time while checking each character to see if it is the end of a line “\n”. If the character is not “\n”, we will throw the current character into a variable, which will create the current line. Once we find “\n” we can output the complete line and start over again compiling the next line. See below: