<?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();
}
PHP高效读大文件处理数据
于 2022-04-20 15:43:49 首次发布