在PHP中读取文件的最后一行

2023年 8月 29日 77.4k 0

在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’函数用于移动到文件末尾或最后一行。读取该行直到遇到换行符。之后,将显示读取的字符。

以上就是在PHP中读取文件的最后一行的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论