Use php to parse the html implementation code, which is usually used by friends who collect data. Recently, to write a crawler using php, you need to parse html and find a project named PHP Simple html dom Parser on sourceforge, it can return the specified DOM element through the css selector in a way similar to jQuery, which is very powerful.
First, introduce the simple_html_dom.php file at the beginning of the program.
Copy codeThe code is as follows:
Include_once ('simple _ html_dom.php ');
PHP Simple html dom Parser provides three methods to create DOM objects.
Copy codeThe code is as follows:
// Create a DOM object from a string
$ Html = str_get_html ('Hello!');
// Create a DOM object from a URL
$ Html = file_get_html ('http: // www.google.com /');
// Create a DOM object from a HTML file
$ Html = file_get_html('test.htm ');
After obtaining the DOM object, you can perform various operations.
Copy codeThe code is as follows:
// Find all anchors, returns a array of element objects
$ Ret = $ html-> find ('A ');
// Find (N) th anchor, returns element object or null if not found (zero based)
$ Ret = $ html-> find ('A', 0 );
// Find lastest anchor, returns element object or null if not found (zero based)
$ Ret = $ html-> find ('A',-1 );
// Find all with the id attribute
$ Ret = $ html-> find ('div [id] ');
// Find all which attribute id = foo
$ Ret = $ html-> find ('div [id = foo] ');
Various css selectors can be used here, just like DOM operations in jQuery, which is very convenient. In addition, there are two special attributes for obtaining text and comments.
Copy codeThe code is as follows:
// Find all text blocks
$ Es = $ html-> find ('text ');
// Find all comment ( ) Blocks
$ Es = $ html-> find ('Comment ');
Of course, similar to jQuery, PHP Simple html dom Parser also supports chained operations and a variety of Simple methods to access DOM elements
Copy codeThe code is as follows:
// Example
Echo $ html-> find ("# div1", 0)-> children (1)-> children (1)-> children (2)-> id;
// Or
Echo $ html-> getElementById ("div1")-> childNodes (1)-> childNodes (1)-> childNodes (2)-> getAttribute ('id ');
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.