问题是使用fseek,所以只能假设性能是一个问题,而file()不是解决方案.这是一个使用fseek的简单方法:
我的file.txt
#file.txt Line 1 Line 2 Line 3 Line 4 Line 5
和代码:
<?PHP $fp = fopen('file.txt','r'); $pos = -2; // Skip final new line character (Set to -1 if not present) $lines = array(); $currentLine = ''; while (-1 !== fseek($fp,$pos,SEEK_END)) { $char = fgetc($fp); if (PHP_EOL == $char) { $lines[] = $currentLine; $currentLine = ''; } else { $currentLine = $char . $currentLine; } $pos--; } $lines[] = $currentLine; // Grab final line var_dump($lines);
输出:
array(5) { [0]=> string(6) "Line 5" [1]=> string(6) "Line 4" [2]=> string(6) "Line 3" [3]=> string(6) "Line 2" [4]=> string(6) "Line 1" }
你不必象我这样追加到$lines数组,如果这是脚本的目的,你可以立即打印输出.如果要限制行数,也很容易引入一个计数器.
$linesToShow = 3; $counter = 0; while ($counter <= $linesToShow && -1 !== fseek($fp,SEEK_END)) { // Rest of code from example. After $lines[] = $currentLine; add: $counter++; }