How to handle excessive memory usage of phpQuery

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.