Get the last 50 lines from a text file using php

I have a text file such as a log file and I want to get the last 50 lines.

How can I do this in PHP?

+4
source share
4 answers

I think you can also use the tail if you are using Linux.

$handle = popen("tail -50l YOUR_FILE_HERE 2>&1", 'r'); while(!feof($handle)) { $buffer = fgets($handle); echo "$buffer<br/>\n"; ob_flush(); flush(); } pclose($handle); 
+4
source

There are some solutions in the comments for the fseek function.

+2
source
 <? $data = file('yourfile.txt'); $lines = implode("\r\n",array_slice($data,count($data)-51,50)); ?> 

Simpler than this

+2
source

I think you can use fopen to get the handle, and then use fileize to get the size and fseek to go to file size -50. Then it's just a five of 50 characters to get the last 50. I think it was done earlier if you look at the manual under fseek.

Here is the solution in fseek manual recording. Just change -1 to the fseek line to -50.

+1
source

All Articles