Read file lines backwards (fgets) with php

前端 未结 4 1895
轮回少年
轮回少年 2021-01-17 18:03

I have a txt file that I want to read backwards, currently I\'m using this:

$fh = fopen(\'myfile.txt\',\'r\');
while ($line = fgets($fh)) {
  echo $line.\"         


        
4条回答
  •  梦毁少年i
    2021-01-17 18:50

    First way:

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

    Second Way (a):

    To completely reverse a file:

    $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);
    
    

    Second Way (b): Of course, you wanted line-by-line reversal...

    
    $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);
    
    

提交回复
热议问题