Read file lines backwards (fgets) with php

fgets, file, php

Solution

First way:

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

Second Way (a):

To completely reverse a file:

$fl = fopen("\some_file.txt", "r");
for($x_pos = 0, $output = ''; fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
    $output .= fgetc($fl);
    }
fclose($fl);
print_r($output);

Second Way (b): Of course, you wanted line-by-line reversal...

$fl = fopen("\some_file.txt", "r");
for($x_pos = 0, $ln = 0, $output = array(); fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
    $char = fgetc($fl);
    if ($char === "\n") {
        // analyse completed line $output[$ln] if need be
        $ln++;
        continue;
        }
    $output[$ln] = $char . ((array_key_exists($ln, $output)) ? $output[$ln] : '');
    }
fclose($fl);
print_r($output);

Problem

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?

Original source