Read a file backwards line by line using fseek

Jeremy Gwa picture Jeremy Gwa · Jul 13, 2010 · Viewed 28.3k times · Source

How do I read a file backwards line by line using fseek?

code can be helpful. must be cross platform and pure php.

many thanks in advance

regards

Jera

Answer

Jonathan Kuhn picture Jonathan Kuhn · Jul 13, 2010

If you are going to read the entire file in anyways, just use file() to read the file in as an array (each line is each element in the array) and then use array_reverse() to flip the array backwards and loop through that. Or just do a reverse for loop where you start at the end and decrement on each loop.

$file = file("test.txt");
$file = array_reverse($file);
foreach($file as $f){
    echo $f."<br />";
}