php - 读取并解析超大文件的内容

标签 php file file-get-contents

<分区>

我正在尝试解析一个大小约为 1GB 的制表符分隔文件。

我在哪里运行我得到的脚本:

Fatal error: Allowed memory size of 1895825408 bytes exhausted  (tried to allocate 1029206974 bytes) ...

我现在的脚本是:

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

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

我已将 php.ini 中的内存限制设置为 -1,这会给我:

Fatal error: Out of memory (allocated 1029963776) (tried to allocate 1029206974 bytes)

有没有办法部分打开文件,然后转到下一部分,从而减少一次使用的内存?

最佳答案

是的,你可以逐行阅读:

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

关于php - 读取并解析超大文件的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14848933/

相关文章:

php - 选择在 CodeIgniter 中显示 MySQL DB 值的位置

php - 我如何用 php 而不是 javascript 编写这个分割

php - file_get_contents() 分解 UTF-8 字符

PHP 发送变量到 file_get_contents()

php - 是否可以使用自定义模式分割文件内容?

php 如何使用循环函数将相同的代码应用于各种数组?

php - 在 PHP 文件中插入译者注释/注释

c - c 上的二进制文件

c - 如何按行 block 处理 C 中的文本文件?

java - JAVA中如何设置写入文件的相对地址?