php使用yield解决Fatal error: Allowed memory size of 134217728 bytes exhausted

发布于 2022-08-17 11:40:31阅读 1044

yield生成器允许你 在 foreach 代码块中写代码来迭代一组数据而不需要在内存中创建一个数组。

错误还原

<?php
$file = './access.log';
$lines=readfile2($file);

foreach($lines as $line){
    file_put_contents('access2.log', $line.PHP_EOL, FILE_APPEND);
}
echo 'ok'.PHP_EOL;

//试图读取一个248M的日志文件,将所有行放到一个数组里面并返回
function readFile2($path){
    $handle = fopen($path, "r");
    $lines=[];
    while (!feof($handle)) {
        $lines[]= fgets($handle);
    }
    fclose($handle);
    return $lines;
}

结果

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 12288 bytes) in /com.docker.devenvironments.code/test.php on line 14

解决办法

这个时候你除了修改代码ini_set('memory_limit', '500M'),或者修改php.ini,你也可以使用 yield ,如下,修改一下 readFile2 函数

function readFile2($path): iterable{
    $handle = fopen($path, "r");

    // $lines=[];
    while (!feof($handle)) {
        // $lines[]= fgets($handle);
        yield fgets($handle);
    }
    fclose($handle);
    // return $lines;
}

广而告之,我的新作品《语音助手》上架Google Play了,欢迎下载体验