file_get_contents = > PHP 致命错误:允许的内存已耗尽

php
2022-08-30 13:47:16

我在处理大文件时没有经验,所以我不知道该怎么办。我试图使用file_get_contents读取几个大文件;任务是使用preg_replace()清洁和咀嚼它们。

我的代码在小文件上运行良好;但是,大文件 (40 MB) 会触发内存耗尽错误:

PHP Fatal error:  Allowed memory size of 16777216 bytes exhausted (tried to allocate 41390283 bytes)

我正在考虑使用fread()代替,但我不确定这是否有效。此问题是否有解决方法?

感谢您的输入。

这是我的代码:

<?php
error_reporting(E_ALL);

##get find() results and remove DOS carriage returns.
##The error is thrown on the next line for large files!
$myData = file_get_contents("tmp11");
$newData = str_replace("^M", "", $myData);

##cleanup Model-Manufacturer field.
$pattern = '/(Model-Manufacturer:)(\n)(\w+)/i';
$replacement = '$1$3';
$newData = preg_replace($pattern, $replacement, $newData);

##cleanup Test_Version field and create comma delimited layout.
$pattern = '/(Test_Version=)(\d).(\d).(\d)(\n+)/';
$replacement = '$1$2.$3.$4      ';
$newData = preg_replace($pattern, $replacement, $newData);

##cleanup occasional empty Model-Manufacturer field.
$pattern = '/(Test_Version=)(\d).(\d).(\d)      (Test_Version=)/';
$replacement = '$1$2.$3.$4      Model-Manufacturer:N/A--$5';
$newData = preg_replace($pattern, $replacement, $newData);

##fix occasional Model-Manufacturer being incorrectly wrapped.
$newData = str_replace("--","\n",$newData);

##fix 'Binary file' message when find() utility cannot id file.
$pattern = '/(Binary file).*/';
$replacement = '';
$newData = preg_replace($pattern, $replacement, $newData);
$newData = removeEmptyLines($newData);

##replace colon with equal sign
$newData = str_replace("Model-Manufacturer:","Model-Manufacturer=",$newData);

##file stuff
$fh2 = fopen("tmp2","w");
fwrite($fh2, $newData);
fclose($fh2);

### Functions.

##Data cleanup
function removeEmptyLines($string)
{
        return preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);
}
?>

答案 1

首先,您应该了解,在使用file_get_contents将整个数据字符串提取到变量中时,该变量存储在主机内存中。

如果该字符串大于专用于 PHP 进程的大小,则 PHP 将暂停并显示上面的错误消息。

解决此问题的方法是将文件作为指针打开,然后一次获取一个块。这样,如果你有一个500MB的文件,你可以读取前1MB的数据,做你想做的事情,从系统内存中删除1MB,然后用下一个MB替换它。这使您可以管理要放入内存的数据量。

如果可以在下面看到这个例子,我将创建一个像node一样的函数.js

function file_get_contents_chunked($file,$chunk_size,$callback)
{
    try
    {
        $handle = fopen($file, "r");
        $i = 0;
        while (!feof($handle))
        {
            call_user_func_array($callback,array(fread($handle,$chunk_size),&$handle,$i));
            $i++;
        }

        fclose($handle);

    }
    catch(Exception $e)
    {
         trigger_error("file_get_contents_chunked::" . $e->getMessage(),E_USER_NOTICE);
         return false;
    }

    return true;
}

然后像这样使用:

$success = file_get_contents_chunked("my/large/file",4096,function($chunk,&$handle,$iteration){
    /*
        * Do what you will with the {$chunk} here
        * {$handle} is passed in case you want to seek
        ** to different parts of the file
        * {$iteration} is the section of the file that has been read so
        * ($i * 4096) is your current offset within the file.
    */

});

if(!$success)
{
    //It Failed
}

您会发现一个问题是,您正在尝试对非常大的数据块执行正则表达式几次。不仅如此,您的正则表达式也是为匹配整个文件而构建的。

使用上述方法,您的正则表达式可能会变得无用,因为您可能只匹配一半数据集。您应该做的是恢复到本机字符串函数,例如

  • strpos
  • substr
  • trim
  • explode

为了匹配字符串,我在回调中添加了支持,以便传递句柄和当前迭代。这将允许您直接在回调中使用文件,例如,允许您使用 和 等函数。fseekftruncatefwrite

构建字符串操作的方式效率不高,使用上面提出的方法是一种更好的方法。

希望这有帮助。


答案 2

一个非常丑陋的解决方案,可以根据文件大小调整内存限制:

$filename = "yourfile.txt";
ini_set ('memory_limit', filesize ($filename) + 4000000);
$contents = file_get_contents ($filename);

正确的解决方案是考虑是否可以在较小的块中处理文件,或者使用PHP中的命令行工具。

如果文件是基于行的,则还可以使用 它来逐行处理。fgets


推荐