Maison > Article > développement back-end > Comment résoudre l’erreur d’épuisement de la mémoire PHP lors de l’utilisation de file_get_contents ?
PHP Memory Exhaustion Error with file_get_contents
Reading extensive files with file_get_contents can lead to a PHP fatal error due to memory exhaustion. For instance, attempting to process 40 MB files triggers the error:
<code class="php">PHP Fatal error: Allowed memory size of 16777216 bytes exhausted (tried to allocate 41390283 bytes)</code>
Alternative Solutions
Instead of file_get_contents, consider these alternatives:
Chunked Reading
By using file_get_contents_chunked function, you can read files in manageable chunks, evitando the memory exhaustion issue.
<code class="php">function file_get_contents_chunked($file, $chunk_size, $callback) { $handle = fopen($file, "r"); $i = 0; while (!feof($handle)) { call_user_func_array($callback, array(fread($handle, $chunk_size), &$handle, $i)); $i++; } fclose($handle); } // Example usage: file_get_contents_chunked("my/large/file", 4096, function($chunk, &$handle, $iteration) {});</code>
Native String Functions
Instead of using regular expressions, consider employing native string functions like strpos, substr, trim, and explode. These functions are more efficient and avoid the potential memory issues.
Regex Optimization
When working with large files, it's crucial to optimize your regex patterns to minimize unnecessary memory consumption. Avoid matching the entire file and instead focus on smaller, specific patterns.
Other Considerations
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!