Using php to parse html implementation code recently I want to write a crawler using php. I 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.
The code is as follows:
Include_once ('simple _ html_dom.php ');
PHP Simple html dom Parser provides three methods to create DOM objects.
The 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.
The 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 ('P [id] ');
// Find all
Which attribute id = foo
$ Ret = $ html-> find ('P [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.
The 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
The code is as follows:
// Example
Echo $ html-> find ("# p1", 0)-> children (1)-> children (1)-> children (2)-> id;
// Or
Echo $ html-> getElementById ("p1")-> childNodes (1)-> childNodes (1)-> childNodes (2)-> getAttribute ('id ');