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

前端 未结 18 1638
陌清茗
陌清茗 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:31

    Opening large files with file() can generate a large array, reserving a considerable chunk of memory.

    You can reduce the memory cost with SplFileObject since it iterates through each line.

    Use the seek method (of seekableiterator) to fetch the last line. You should then subtract the current key value by 5.

    To obtain the last line, use PHP_INT_MAX. (Yes, this is a workaround.)

    $file = new SplFileObject('large_file.txt', 'r');
    
    $file->seek(PHP_INT_MAX);
    
    $last_line = $file->key();
    
    $lines = new LimitIterator($file, $last_line - 5, $last_line);
    
    print_r(iterator_to_array($lines));
    

提交回复
热议问题