Read file lines backwards (fgets) with php

Viewed 12362

I have a txt file that I want to read backwards, currently I'm using this:

$fh = fopen('myfile.txt','r');
while ($line = fgets($fh)) {
  echo $line."<br />";
}

This outputs all the lines in my file.
I want to read the lines from bottom to top.

Is there a way to do it?

5 Answers

Here's my simple solution without messing up anything or adding more complex code

$fh = fopen('myfile.txt','r');
while ($line = fgets($fh)) {
  $result = $line . "<br>" . $result;
}
echo $result // or return $result if you are using it as a function
Related