我在處理大文件時沒有經驗,所以我不知道該怎麼做。我試圖使用file_get_contents來讀取幾個大文件;任務是使用preg_replace()進行清理並將它們打包。file_get_contents => PHP致命錯誤:允許內存耗盡
我的代碼在小文件上運行良好;但是,大文件(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);
}
?>
您可能可以使用'fread()'以塊的形式獲取它,但是否會對您有所幫助取決於您對其執行的操作類型以及對結果的處理方式。 – 2011-03-09 16:58:29
嘿克里斯。 php.ini文件中有一個用於處理文件/內存大小的屬性。如果我記得,你可以改變數字來增加尺寸。這將/應該允許您處理較大的文件。 – 2011-03-09 16:59:29
@tom史密斯:這不是我的服務器,可悲的是,我的手被綁起來。 – Chris 2011-03-09 17:34:19