How to read a large file line by line?

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

    SplFileObject is useful when it comes to dealing with large files.

    function parse_file($filename)
    {
        try {
            $file = new SplFileObject($filename);
        } catch (LogicException $exception) {
            die('SplFileObject : '.$exception->getMessage());
        }
        while ($file->valid()) {
            $line = $file->fgets();
            //do something with $line
        }
    
        //don't forget to free the file handle.
        $file = null;
    }
    

提交回复
热议问题