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 ('// 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 <div> with the id attribute
$ Ret = $ html-> find ('div [id] ');
// Find all <div> 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 ');