Home >Backend Development >PHP Tutorial >Implementation code for parsing html with php_PHP tutorial

Implementation code for parsing html with php_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:25:05807browse

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 file simple_html_dom.php at the beginning of the program

Copy the code The code is as follows:

include_once(' simple_html_dom.php');

PHP Simple HTML DOM Parser provides 3 ways to create DOM objects
Copy code Code 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 getting the DOM object, you can perform various operations
Copy 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
with the id attribute
$ret = $html->find('div[id]');
// Find all
which attribute id=foo
$ret = $html->find('div[ id=foo]');

You can use various css selectors here, just like DOM operations in jQuery, which is very convenient. In addition, there are two special attributes to get the content of text and comments
Copy code 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 chain operations and various simple methods of accessing DOM elements
Copy 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');

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324200.htmlTechArticleRecently I want to use PHP to write a crawler, which requires parsing HTML. I found a project called PHP Simple HTML DOM on sourceforge. Parser, which can be returned via css selectors in a jQuery-like manner...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn