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 ?

Comment résoudre l’erreur d’épuisement de la mémoire PHP lors de l’utilisation de file_get_contents ?

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2024-10-17 13:35:30248parcourir

How to Resolve PHP Memory Exhaustion Error When Using 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

  • Increase PHP memory limit: You can temporarily increase the PHP memory limit to accommodate larger file processing.
  • Use a dedicated database: For persistent data storage, consider using a database instead of manipulating large files in memory.

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!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn