开发者

PHP: fgets equivalent for reading from the _bottom_ of a file?

开发者 https://www.devze.com 2023-04-02 07:55 出处:网络
I have a file that updates itself by appending,however this file becomes huge (500MB). I would like 开发者_C百科to read the last 50 lines in the file. How can this be done?Tail -n50 will return the la

I have a file that updates itself by appending, however this file becomes huge (500MB). I would like 开发者_C百科to read the last 50 lines in the file. How can this be done?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消