使用 phpQuery 批量解析網頁時,內存迅速飆升(>1GB),甚至觸發 OOM。原因:phpQuery 內部靜態屬性 $documents 保存所有歷史 DOMDocumentWrapper 實例,未主動釋放。
// phpQuery.php 內部
static public $documents = [];
public static function createDocumentWrapper($doc) {
$wrapper = new DOMDocumentWrapper($doc);
self::$documents[$wrapper->id] = $wrapper; // 每次解析添加一個,永不清理
return $wrapper;
}
while (true) {
phpQuery::newDocumentFile($htmlFile);
// 處理頁面元素...
// 關鍵:每次解析完清空靜態緩存
phpQuery::$documents = [];
echo memory_get_usage() . "\n"; // 內存穩定
}
function parseWithPhpQuery($html) {
phpQuery::newDocumentHTML($html);
try {
// 業務解析邏輯
$data = pq('.target')->html();
return $data;
} finally {
// 確保異常時也能清理
phpQuery::$documents = [];
phpQuery::unloadDocuments(); // 部分版本提供
}
}