Home >Backend Development >PHP Tutorial >http://www.google.com.hk/ Implementation code for parsing html using php

http://www.google.com.hk/ Implementation code for parsing html using php

WBOY
WBOYOriginal
2016-07-29 08:46:301538browse

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');


PHP Simple HTML DOM Parser provides 3 ways to Create a DOM object

Copy the code The code is as follows:


// Create a DOM object from a string
$html = str_get_html('Hello!< /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 getting the DOM object, you can perform various operations

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

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 the code The code is as follows:


// Find all text blocks
$es = $html->find('text' );
// Find all comment () blocks
$es = $html->find('comment');


Of course, it is still similar to jQuery, PHP Simple HTML DOM Parser also supports chain operations and various simple methods to access DOM elements

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.

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