I have a file that updates itself by appending, however this file becomes huge (500MB). I would like to read the last 50 lines in the file. How can this be done?
Asked
Active
Viewed 226 times
2 Answers
4
Tail -n50 will return the last 50 lines of the file.
$filename = 'test.html';
$output = shell_exec('exec tail -n50 ' . $filename);
echo $output;
Therefore, you don't have to load the entire file in memory.
Edit:
If you want to echo "<br>
" after each line you do:
echo str_replace(PHP_EOL, '<br />', $output);

Book Of Zeus
- 49,509
- 18
- 174
- 171
3
You'll need to use fseek
to move the file pointer a certain number of bytes from the end of the file:
$fp = fopen('myfile','r');
fseek($fp,-1024, SEEK_END);
$last_kb_of_file = fgets($fp,1024);
You'll have to tell fgets
how many bytes you want to read, not how many lines. It has no idea what the format of the file is. You'll have to split the result on a newline and see if you have 50 lines.

Christopher Armstrong
- 7,907
- 2
- 26
- 28
` after each line? – dukevin Sep 03 '11 at 00:35