Home >Backend Development >PHP Tutorial >http://www.google.com.hk/ Implementation code for parsing html using php
Recently I want to use PHP to write a crawler, which requires parsing HTML. I found a project called PHP Simple HTML DOM Parser on sourceforge. It can return specified DOM elements through a CSS selector in a jQuery-like way. It is very powerful.
First introduce the simple_html_dom.php file at the beginning of the program
Copy the code The code is as follows:
include_once('simple_html_dom.php');
Copy the code The code is as follows:
// Create a DOM object from a string
$html = str_get_html('
Copy the code The code is as follows:
// Find all anchors, returns an 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
Copy the code The code is as follows:
// Find all text blocks
$es = $html->find('text' );
// Find all comment () blocks
$es = $html->find('comment');
Copy the code The 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 above introduces the implementation code of http://www.google.com.hk/ using PHP to parse HTML, including the content of http://www.google.com.hk/. I hope that friends are interested in PHP tutorials. Helps.