This article solves the problem of excessive memory usage in phpQuery. phpQuery is an open-source project similar to jQuery implemented in php. it can parse web page elements in the form of jQuery syntax on the server side. Compared with regular expressions or other methods that match web pages, phpQuery is much easier to use.
When using phpQuery to collect webpages, I encountered a problem: after processing a large number of webpages, the memory occupied by phpQuery is amazing (it soon exceeded 1 GB ),
For example, this code:
The code is as follows:
While (true ){
PhpQuery: newDocumentFile ($ htmlFile );
// Process webpage elements...
Echo memory_get_usage (). "\ n ";
}
Run the above code with caution and it will soon use up your memory.
After checking the source code of phpQuery, the problem is finally found. each time phpQuery processes a webpage, a DOMDocumentWrapper object is generated, and each DOMDocumentWrapper object is saved in the static member $ documents (phpQuery:: createDocumentWrapper). This variable is an array. each time a webpage array element is parsed, it is added.
PhpQuery: $ documents [$ wrapper-> id] = $ wrapper;
After finding the problem, it is easy to solve it. after parsing a webpage, leave phpQuery: $ documents Ents blank.
The code is as follows:
While (true ){
PhpQuery: newDocumentFile ($ htmlFile );
// Process webpage elements...
PhpQuery: $ documents ents = array ();
Echo memory_get_usage (). "\ n ";
}
Memory usage is stable.