在使用phpquery采集网页时,遇到一个问题:在处理大量网页之后,phpquery占用的内存数量非常惊人(很快就超过了1g),
比如这段代码:
复制代码 代码如下:
while (true) {
phpquery::newdocumentfile($htmlfile);
// 处理网页元素...
echo memory_get_usage() . "n";
}
谨慎运行上面这段代码,它会很快用光你的内存。
经过查看phpquery的源代码终于发现了问题所在,phpquery在每处理一个网页就会产生一个domdocumentwrapper 对象,而每个domdocumentwrapper 对象会被保存在静态成员$documents中(phpquery::createdocumentwrapper中),这个变量是一个数组,每解析一个网页数组元素就增加一个。
phpquery::$documents[$wrapper->id] = $wrapper;
找到问题后,解决就很容易了,每次解析完一个网页,把phpquery::$documents置空即可。
复制代码 代码如下:
while (true) {
phpquery::newdocumentfile($htmlfile);
// 处理网页元素...
phpquery::$documents = array();
echo memory_get_usage() . "n";
}
内存占用稳定了。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!