How to read a large file line by line?

后端 未结 14 1017
[愿得一人]
[愿得一人] 2020-11-22 00:21

I want to read a file line by line, but without completely loading it in memory.

My file is too large to open in memory, and if try to do so I always get out of memo

相关标签:
14条回答
  • 2020-11-22 01:19

    The obvious answer wasn't there in all the responses.
    PHP has a neat streaming delimiter parser available made for exactly that purpose.

    $fp = fopen("/path/to/the/file", "r+");
    while (($line = stream_get_line($fp, 1024 * 1024, "\n")) !== false) {
      echo $line;
    }
    fclose($fp);
    
    0 讨论(0)
  • 2020-11-22 01:22

    One of the popular solutions to this question will have issues with the new line character. It can be fixed pretty easy with a simple str_replace.

    $handle = fopen("some_file.txt", "r");
    if ($handle) {
        while (($line = fgets($handle)) !== false) {
            $line = str_replace("\n", "", $line);
        }
        fclose($handle);
    }
    
    0 讨论(0)
提交回复
热议问题