Reading large files from end

前端 未结 10 1538
慢半拍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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-28 20:17

    For Linux you can do

    $linesToRead = 10;
    exec("tail -n{$linesToRead} {$myFileName}" , $content); 
    

    You will get an array of lines in $content variable

    Pure PHP solution

    $f = fopen($myFileName, 'r');
    
        $maxLineLength = 1000;  // Real maximum length of your records
        $linesToRead = 10;
        fseek($f, -$maxLineLength*$linesToRead, SEEK_END);  // Moves cursor back from the end of file
        $res = array();
        while (($buffer = fgets($f, $maxLineLength)) !== false) {
            $res[] = $buffer;
        }
    
        $content = array_slice($res, -$linesToRead);
    

提交回复
热议问题