Reading large files from end

前端 未结 10 1541
慢半拍i
慢半拍i 2020-12-28 19:47

Can I read a file in PHP from my end, for example if I want to read last 10-20 lines?

And, as I read, if the size of the file is more than 10mbs I start getting erro

10条回答
  •  既然无缘
    2020-12-28 20:11

    If your code is not working and reporting an error you should include the error in your posts!

    The reason you are getting an error is because you are trying to store the entire contents of the file in PHP's memory space.

    The most effiicent way to solve the problem would be as Greenisha suggests and seek to the end of the file then go back a bit. But Greenisha's mecanism for going back a bit is not very efficient.

    Consider instead the method for getting the last few lines from a stream (i.e. where you can't seek):

    while (($buffer = fgets($handle, 4096)) !== false) {
        $i1++;
        $content[$i1]=$buffer;
        unset($content[$i1-$lines_to_keep]);
    }
    

    So if you know that your max line length is 4096, then you would:

    if (4096*lines_to_keep

    Then apply the loop I described previously.

    Since C has some more efficient methods for dealing with byte streams, the fastest solution (on a POSIX/Unix/Linux/BSD) system would be simply:

    $last_lines=system("last -" . $lines_to_keep . " filename");
    

提交回复
热议问题