下面的代码在一个循环中。每个循环将 URL 更改为新地址。我的问题是每次通过都会占用越来越多的内存。
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://site.ru/');
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, 'http://site.ru/');
curl_setopt($ch, CURLOPT_HEADER, false);
$html = new \DOMDocument();
$html->loadHTML(curl_exec($ch));
curl_close($ch);
$ch = null;
$xpath = new \DOMXPath($html);
$html = null;
foreach ($xpath->query('//*[@id="tree"]/li[position() > 5]') as $category) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $xpath->query('./a', $category)->item(0)->nodeValue);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, 'http://site.ru/');
curl_setopt($ch, CURLOPT_HEADER, false);
$html = new \DOMDocument();
$html->loadHTML(curl_exec($ch));
curl_close($ch);
$ch = null;
// etc.
}
内存为 2000 Mb。脚本执行时间~2h。 PHP 版本 5.4.4。 如何避免内存泄漏?谢谢!
最佳答案
互联网上的故事表明 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)
在某些 PHP/cURL 版本中被破坏:
- #13225 Memmory leak in curl
- #40831 cURL extension doesnt clear buffer for reused handle
- PHP script memory leak issue
- PHP cURL, memory leak when using CURLOPT_RETURNTRANSFER
您还可以找到 DOM
的故事:
- DOMDocument PHP Memory Leak
- PHP/DOMDocument: unset() does not release resources
- DOMDocument / Xpath leaking memory during long command line process - any way to deconstruct this class
创建一个最小的测试用例来找出泄漏的原因。 IE。从代码中删除不相关的包(DOM 或 cURL)。
然后用最新的 PHP 版本重现它。如果它仍然导致泄漏,file a bug report否则使用该 PHP 版本。
关于PHP cUrl 循环泄漏内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26690026/