
使用File_get_contents 進行檔案處理遇到記憶體耗盡
PHP 中處理大型檔案時,使用file_get_contents 函數將整個檔案內容獲取到變數可能會導致記憶體耗盡錯誤。這是因為包含文件內容的變數駐留在記憶體中,對於大文件,可能會超出分配的記憶體限制。
為了克服這個問題,更有效的方法是使用檔案指標並處理檔案分塊。這樣,在任何給定時間,只有檔案的當前部分保存在記憶體中。
這是實作此分塊檔案處理的自訂函數:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <code class = "php" > function file_get_contents_chunked( $file , $chunk_size , $callback )
{
try {
$handle = fopen ( $file , "r" );
$i = 0;
while (! feof ( $handle )) {
call_user_func_array( $callback , [ fread ( $handle , $chunk_size ), & $handle , $i ]);
$i ++;
}
fclose( $handle );
return true;
} catch (Exception $e ) {
trigger_error( "file_get_contents_chunked::" . $e ->getMessage(), E_USER_NOTICE);
return false;
}
}</code>
|
登入後複製
要使用此函數,定義一個回調函數來處理每個資料區塊:
1 2 3 | <code class = "php" > $success = file_get_contents_chunked( "my/large/file" , 4096, function ( $chunk , & $handle , $iteration ) {
});</code>
|
登入後複製
此外,請考慮重構您的正規表示式操作以使用本機字串函數,例如strpos、substr、trim 和explode。這可以顯著提高處理大檔案時的效能。
以上是在 PHP 中使用 File_get_contents 處理大檔案時如何避免記憶體耗盡?的詳細內容。更多資訊請關注PHP中文網其他相關文章!