如果你不介意加載整個文件到內存:
$lines = array_slice(file('test.txt'), -15);
print_r($lines);
如果文件過大而無法裝入內存,你可以使用一個圓形的方法:
// Read the last $num lines from stream $fp
function read_last_lines($fp, $num)
{
$idx = 0;
$lines = array();
while(($line = fgets($fp)))
{
$lines[$idx] = $line;
$idx = ($idx + 1) % $num;
}
$p1 = array_slice($lines, $idx);
$p2 = array_slice($lines, 0, $idx);
$ordered_lines = array_merge($p1, $p2);
return $ordered_lines;
}
// Open the file and read the last 15 lines
$fp = fopen('test.txt', 'r');
$lines = read_last_lines($fp, 15);
fclose($fp);
// Output array
print_r($lines);
這種方法如果文件少於15行,也將工作 - 返回一個數組,但文件中有很多行。
我出closevotes的和過於勞累熬夜35分鐘,但無論如何:可能重複[PHP如何只讀5 txt文件的最後一行(http://stackoverflow.com/問題/ 2961618/php-how-to-read-only-5-last-line-of-txt-file) – Gordon 2010-08-25 23:24:40
另一個http://stackoverflow.com/questions/514673/how-do-i-open -a-file-from-line -x-to-line -y-in-php – Gordon 2010-08-25 23:32:40