Search code examples
phpfopen

How to read only 5 last line of the text file in PHP?


I have a file named file.txt which is update by adding lines to it.

I am reading it by this code:

$fp = fopen("file.txt", "r");
$data = "";
while(!feof($fp))
{
$data .= fgets($fp, 4096);
}
echo $data;

and a huge number of lines appears. I just want to echo the last 5 lines of the file

How can I do that ?


The file.txt is like this:

11111111111111
22222222222

33333333333333
44444444444

55555555555555
66666666666

Solution

  • Untested code, but should work:

    $file = file("filename.txt");
    for ($i = max(0, count($file)-6); $i < count($file); $i++) {
      echo $file[$i] . "\n";
    }
    

    Calling max will handle the file being less than 6 lines.