Recently want to use PHP to write a crawler, you need to parse the HTML, on the SourceForge to find a project called PHP simple HTML DOM Parser, it can be in a similar way jquery through the CSS selector to return the specified DOM elements, the function is very powerful.
First, introduce the simple_html_dom.php file at the beginning of the program.
Copy Code code as follows:
Include_once (' simple_html_dom.php ');
PHP Simple HTML DOM Parser provides 3 ways to create a DOM object
Copy Code code 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 you get the DOM object, you can do all sorts of things.
Copy Code code 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] ');
You can use a variety of CSS selectors, just as you would for Dom in jquery. In addition, there are two special properties to get text and annotation content
Copy Code code as follows:
Find all text blocks
$es = $html->find (' text ');
Find all comment (<!--...-->) blocks
$es = $html->find (' comment ');
Of course, it's similar to jquery,php simple HTML DOM parser also supports chained operations, and a variety of easy ways to access DOM elements
Copy Code code 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 ');