PHP高效读大文件处理数据

<?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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值