在 PHP 中读取文件最后一行


要从文件读取 PHP 的最后一行,代码如下所示 −

$line = '';
$f = fopen('data.txt', 'r');
$cursor = -1;
fseek($f, $cursor, SEEK_END);
$char = fgetc($f);
//Trim trailing newline characters in the file
while ($char === "
" || $char === "\r") {    fseek($f, $cursor--, SEEK_END);    $char = fgetc($f); } //Read until the next line of the file begins or the first newline char while ($char !== false && $char !== "
" && $char !== "\r") {    //Prepend the new character    $line = $char . $line;    fseek($f, $cursor--, SEEK_END);    $char = fgetc($f); } echo $line;

输出将是读取并显示文本文件的最后一行。

文本文件以读取模式打开,并且光标设置为指向 -1,即最初什么都不指向。‘fseek’ 函数用于移动到文件或最后一行末尾。该行读取直到遇到换行符。此后,显示读取的字符。

更新于: 09-4-2020

3k+ 浏览

开始你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.