Wie vermeide ich Speichererschöpfung bei der Verarbeitung großer Dateien in PHP mit File_get_contents?

Patricia Arquette
Freigeben: 2024-10-17 13:37:02
Original
370 Leute haben es durchsucht

How to Avoid Memory Exhaustion When Processing Large Files in PHP Using File_get_contents?

File Processing Using File_get_contents Encounters Memory Exhaustion

When working with large files in PHP, using the file_get_contents function to fetch the entire file contents into a variable can cause memory exhaustion errors. This is because the variable containing the file contents resides in memory, and for large files, the allocated memory limit can be exceeded.

To overcome this issue, a more efficient approach is to use file pointers and process the file in chunks. This way, only the current portion of the file is held in memory at any given time.

Here's a custom function that implements this chunked file processing:

<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>
Nach dem Login kopieren

To use this function, define a callback function to handle each chunk of data:

<code class="php">$success = file_get_contents_chunked("my/large/file", 4096, function($chunk, &$handle, $iteration) {
    // Perform file processing here
});</code>
Nach dem Login kopieren

Additionally, consider refactoring your regex operations to use native string functions like strpos, substr, trim, and explode. This can significantly improve performance when working with large files.

Das obige ist der detaillierte Inhalt vonWie vermeide ich Speichererschöpfung bei der Verarbeitung großer Dateien in PHP mit File_get_contents?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!