读取并解析非常大的文件的内容

imp*_*335 8 php file file-get-contents

我试图解析一个大小约1GB的制表符分隔文件.

在哪里运行脚本我得到:

Fatal error: Allowed memory size of 1895825408 bytes exhausted  (tried to allocate 1029206974 bytes) ...
Run Code Online (Sandbox Code Playgroud)

我的剧本目前只是:

$file = file_get_contents('allCountries.txt') ;

$file = str_replace(array("\r\n", "\t"), array("[NEW*LINE]", "[tAbul*Ator]"), $file) ;
Run Code Online (Sandbox Code Playgroud)

我已经将php.ini中的内存限制设置为-1,然后给了我:

Fatal error: Out of memory (allocated 1029963776) (tried to allocate 1029206974 bytes)
Run Code Online (Sandbox Code Playgroud)

是否有部分打开文件,然后继续下一部分,以便一次使用更少的内存?

Ran*_*nty 11

是的,你可以逐行阅读:

$handle = @fopen("/tmp/inputfile.txt", "r");
if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
        echo $buffer;
    }
    fclose($handle);
}
Run Code Online (Sandbox Code Playgroud)