Reading large files from end

前端 未结 10 1549
慢半拍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条回答
  •  Happy的楠姐
    2020-12-28 20:13

    If you know about how long the lines are, you can avoid a lot of the black magic and just grab a chunk of the end of the file.

    I needed the last 15 lines from a very large log file, and altogether they were about 3000 characters. So I just grab the last 8000 bytes to be safe, then read the file as normal and take what I need from the end.

        $fh = fopen($file, "r");
        fseek($fh, -8192, SEEK_END);
        $lines = array();
        while($lines[] = fgets($fh)) {}
    

    This is possibly even more efficient than the highest rated answer, which reads the file character by character, compares each character, and splits based on newline characters.

提交回复
热议问题