Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file lines backwards (fgets) with php

Tags:

file

php

fgets

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?

like image 271
Nir Tzezana Avatar asked Dec 13 '13 07:12

Nir Tzezana


Video Answer


2 Answers

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);

like image 78
sergio Avatar answered Oct 14 '22 09:10

sergio


If the file is not so big you can use file():

$lines = file($file);
for($i = count($lines) -1; $i >= 0; $i--){
    echo $lines[$i] . '<br/>';
}

However, this requires the whole file to be in memory, that's why it is not suited for really large files.

like image 39
hek2mgl Avatar answered Oct 14 '22 09:10

hek2mgl