如何使用PHP读取和回显TEXT文件中最后一行之前的N行?
file.txt中的示例
test1
test2
test3
test4
test5
test6
test7
我想获取最后一行的值和最后一行之前的3行。 结果将是:
test4
test7
到目前为止,这是我的代码(只显示最后一行)
$line = '';
$f = fopen('\\\\192.168.183.28\\wk$\\sbin\\file.txt', 'r');
$cursor = -1;
fseek($f, $cursor, SEEK_END);
$char = fgetc($f);
while ($char === "\n" || $char === "\r") {
fseek($f, $cursor--, SEEK_END);
$char = fgetc($f);
}
while ($char !== false && $char !== "\n" && $char !== "\r")
{
$line = $char . $line;
fseek($f, $cursor--, SEEK_END);
$char = fgetc($f);
}
$future_sn = substr($line, 28, 36);
有什么建议吗?
答案 0 :(得分:0)
您可以使用fgets()读取文件并保留计数器以跟踪最后一行。你可以通过mod(%)计数器从最后一步获得3行。
$handle = fopen("input.txt", "r");
$lastRow = "";
$last3Ahead = "";
$counter = 0;
$a = "";
$b = "";
$c = "";
if ($handle) {
while (($line = fgets($handle)) !== false) {
if($counter == 0) $a = $line;
if($counter == 1) $b = $line;
if($counter == 2) $c = $line;
$lastRow = $line ;
if($counter >= 3) {
$last3Ahead = $a;
$a = $b;
$b = $c;
$c = $line
}
$counter++;
} else {
// error opening the file.
}
fclose($handle);
echo $lastRow. "<br>" ; //last row
echo $last3Ahead . "<br>"; //3 row before last;
答案 1 :(得分:0)
试
$array = explode("\n", file_get_contents('file.txt'));
// counting array and get key for prev
$prev_third = count($array)-4;
echo end($array); // test7
echo $array[$prev_third]; //test4