Home  >  Article  >  Backend Development  >  Implementation code for parsing html with php

Implementation code for parsing html with php

高洛峰
高洛峰Original
2016-11-30 11:10:031438browse

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
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 getting the DOM object Various operations can be performed
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]');

Various css selectors can be used here, just like in It is very convenient to perform DOM operations in jQuery. 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 chaining Operations, as well as 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');

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