Get the last 50 lines from text file using php

后端 未结 4 620
灰色年华
灰色年华 2020-12-19 14:49

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

How can I do it, in PHP?

相关标签:
4条回答
  • 2020-12-19 14:59

    I think you can use fopen to get the handle, then use filesize to get the size and fseek to go to filesize-50. Then it's just fread of 50 characters to get the last 50. I imagine this ha been done before if you look at the manual under fseek.

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

    0 讨论(0)
  • 2020-12-19 15:11

    There are some sollutions in comments for function fseek.

    0 讨论(0)
  • 2020-12-19 15:13
    <?
    $data = file('yourfile.txt');
    $lines = implode("\r\n",array_slice($data,count($data)-51,50));
    ?>
    

    As simple as this

    0 讨论(0)
  • 2020-12-19 15:22

    I guess you could also be using "tail" if you are on 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);
    
    0 讨论(0)
提交回复
热议问题