当前位置:网站首页>PHP高效读大文件处理数据

PHP高效读大文件处理数据

2022-04-23 16:44:00 代元培

<?php

// 直接用file()会报致命错误 内存耗尽;如 $file = file($file);
// 报错内容 取决于memory_limit配置 
// Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 840860368 bytes) in /home/work/*.php on line *

// php bigFileRead.php test.txt

if(!isset($argv[1])){
    echo 'The first parameter is null. =>>> [php bigFileRead.php 1.txt]'.PHP_EOL;die;
}else{
    $file = $argv[1];
    if(!file_exists($file)){
        echo 'file does not exist.'.PHP_EOL;die;
    }
}

function effReadFile($path){
    if($handle = fopen($path, 'r')){
        // 函数检查是否已到达文件末尾
        while(!feof($handle)){
            yield trim(fgets($handle));
        }
        fclose($handle);
    }
}
// 读大文件 使用
$glob = effReadFile($file);
while ($glob->valid()) {
    // 当前行文本
    $line = $glob->current();
    // 逐行处理数据
    echo $line.PHP_EOL;
    // 指向下一个,不能少
    $glob->next();
}

版权声明
本文为[代元培]所创,转载请带上原文链接,感谢
https://blog.csdn.net/sosemseo/article/details/124299137