How to read only 5 last line of the text file in PHP?

前端 未结 18 1655
陌清茗
陌清茗 2020-11-28 08:45

I have a file named file.txt which is update by adding lines to it.

I am reading it by this code:

$fp = fopen(\"file.txt\", \"r\");
$da         


        
18条回答
  •  天涯浪人
    2020-11-28 09:10

    FAST

    Here is FAST method for LARGE files with LOW memory cost - I develop Wallace Maxters answer (if you want to upvote - do it on his answer) by wrap his code inside handy function and add reverse feature

    function readLastLines($filename, $num, $reverse = false)
    {
        $file = new \SplFileObject($filename, 'r');
        $file->seek(PHP_INT_MAX);
        $last_line = $file->key();
        $lines = new \LimitIterator($file, $last_line - $num, $last_line);
        $arr = iterator_to_array($lines);
        if($reverse) $arr = array_reverse($arr);
        return implode('',$arr);
    }
    
    // use it by
    $lines = readLastLines("file.txt", 5) // return string with 5 last lines
    

提交回复
热议问题