How to read a large file line by line?

后端 未结 14 1014
[愿得一人]
[愿得一人] 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 00:58

    If you're opening a big file, you probably want to use Generators alongside fgets() to avoid loading the whole file into memory:

    /**
     * @return Generator
     */
    $fileData = function() {
        $file = fopen(__DIR__ . '/file.txt', 'r');
    
        if (!$file)
            die('file does not exist or cannot be opened');
    
        while (($line = fgets($file)) !== false) {
            yield $line;
        }
    
        fclose($file);
    };
    

    Use it like this:

    foreach ($fileData() as $line) {
        // $line contains current line
    }
    

    This way you can process individual file lines inside the foreach().

    Note: Generators require >= PHP 5.5

提交回复
热议问题