卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章16449本站已运行3317

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

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

卓越飞翔博客
上一篇: 探索 3 个掌握 WordPress 插件开发的实践项目
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏