php - 使用 php 向后读取文件行(fgets)

标签 php file fgets

我有一个 txt 文件,我想向后阅读,目前我正在使用这个:

$fh = fopen('myfile.txt','r');
while ($line = fgets($fh)) {
  echo $line."<br />";
}

这会输出我文件中的所有行。
我想从下到上阅读这些行。

有办法吗?

最佳答案

第一种方式:

$file = file("test.txt");
$file = array_reverse($file);
foreach($file as $f){
    echo $f."<br />";
}

第二种方式(a):

要完全反转一个文件:

$fl = fopen("\some_file.txt", "r");
for($x_pos = 0, $output = ''; fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
    $output .= fgetc($fl);
    }
fclose($fl);
print_r($output);

第二种方式(b): 当然,你想要逐行反转......


$fl = fopen("\some_file.txt", "r");
for($x_pos = 0, $ln = 0, $output = array(); fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
    $char = fgetc($fl);
    if ($char === "\n") {
        // analyse completed line $output[$ln] if need be
        $ln++;
        continue;
        }
    $output[$ln] = $char . ((array_key_exists($ln, $output)) ? $output[$ln] : '');
    }
fclose($fl);
print_r($output);

关于php - 使用 php 向后读取文件行(fgets),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20561480/

相关文章:

java - BufferedReader readLine 返回 null

c - C编程中的strstr()函数

php - Lumen 中 URL 没有参数时重定向

php - 同一用户登录具有不同数据库的不同 WordPress 域

python - 如何读取一些文件数据并将其写入另一个文件?

c++ - 如果我打开文件后有人覆盖该文件会怎样?

javascript - Codeigniter AJAX 通过 POST 将数组传递到另一个页面

php - 什么会导致 crypt 产生错误的验证?

C - 带有嵌套 fgets 循环的 fork 和管道

c - 我如何使用 2 个单独的函数 "fgets"写入 2 个单独的变量?