PHP DOMDocument memory leak

Running PHP 5.3.6 under MAMP on a MAC, memory usage increases every x calls (between 3 and 8) until the script dies from running out of memory. How to fix it?

libxml_use_internal_errors(true); while(true){ $dom = new DOMDocument(); $dom->loadHTML(file_get_contents('http://www.ebay.com/')); unset($dom); echo memory_get_peak_usage(true) . '<br>'; flush(); } 
+6
source share
4 answers

Using libxml_use_internal_errors(true); suppresses error output, but builds a continuous error log that is added to each cycle. Either turn off internal logging and suppress PHP warnings, or clear the internal log at each loop iteration as follows:

 <?php libxml_use_internal_errors(true); while(true){ $dom = new DOMDocument(); $dom->loadHTML(file_get_contents('ebay.html')); unset($dom); libxml_use_internal_errors(false); libxml_use_internal_errors(true); echo memory_get_peak_usage(true) . "\r\n"; flush(); } ?> 
+16
source

You can try to get the garbage collector to work with gc_collect_cycles() , but otherwise you're out of luck. PHP does not allocate anything that could control its use of internal memory, not to mention the memory used by the plugin library.

+1
source

Based on @Tak's answer and @FrancisAvila's comment, I found that these snippings work better for me:

 while (true) { $dom = new DOMDocument(); if (libxml_use_internal_errors(true) === true) // previous setting was true? { libxml_clear_errors(); } $dom->loadHTML(file_get_contents('ebay.html')); } print_r(libxml_get_errors()); // errors from the last iteration are accessible 

This has the following advantages: 1) do not discard parsing errors last if you ever need to access them through libxml_get_errors() , and 2) calling libxml_clear_errors() only if necessary, since libxml_use_internal_errors() returns the previous configuration state.

+1
source

Testing your script locally gives the same result. However, changing file_get_contents() in a local HTML file provides consistent memory usage. Perhaps the result of ebay.com changes every X-call.

0
source

Source: https://habr.com/ru/post/903066/


All Articles