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
Das obige ist der detaillierte Inhalt vonWie behebt man den PHP-Speicherauslastungsfehler bei Verwendung von file_get_contents?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!