如何使用 fseek 逐行向后读取文件?
代码可能会有所帮助。必须是跨平台的、纯php的。
提前谢谢了
regards
Jera
问题是使用 fseek 询问,因此只能假设性能是一个问题,而 file() 不是解决方案。这是使用 fseek 的简单方法:
我的文件.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);
Output:
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, $pos, SEEK_END)) {
// Rest of code from example. After $lines[] = $currentLine; add:
$counter++;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)