```php
解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。
它使用了类似jQuery的元素选择器,通过元素的id,class,tag等等来查找定位;
同时还提供添加、删除、修改文档树的功能。当然,这样一款强大的html Dom解析
器也不是尽善尽美;在使用的过程中需要十分小心内存消耗的情况。不过,不要担心;
本文中,笔者在最后会为各位介绍如何避免消耗过多的内存。
开始使用
上传类文件以后,有三种方式调用这个类:
从url中加载html文档
从字符串中加载html文档
从文件中加载html文档
// 新建一个Dom实例
$html = new simple_html_dom();
// 从url中加载
$html->load_file('http://www.jb51.net');
// 从字符串中加载
$html->load('
从字符串中加载html文档演示');//从文件中加载
$html->load_file('path/file/test.html');
?>
如果从字符串加载html文档,需要先从网络上下载。建议使用CURL来抓取html文档并加载DOM中。
PHP Simple HTML DOM Parser提供了3种方式来创建DOM对象 :
// 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');
查找html元素
可以使用find函数来查找html文档中的元素。返回的结果是一个包含了对象的数组。
我们使用HTML DOM解析类中的函数来访问这些对象,下面给出几个示例:
//查找html文档中的超链接元素
$a = $html->find('a');
//查找文档中第(N)个超链接,如果没有找到则返回空数组.
$a = $html->find('a', 0);
// 查找id为main的div元素
$main = $html->find('div[id=main]',0);
// 查找所有包含有id属性的div元素
$divs = $html->find('div[id]');
// 查找所有包含有id属性的元素
$divs = $html->find('[id]');
?>
还可以使用类似jQuery的选择器来查找定位元素:
// 查找id='#container'的元素
$ret = $html->find('#container');
// 找到所有class=foo的元素
$ret = $html->find('.foo');
// 查找多个html标签
$ret = $html->find('a, img');
// 还可以这样用
$ret = $html->find('a[title], img[title]');
?>
解析器支持对子元素的查找
// 查找 ul列表中所有的li项
$ret = $html->find('ul li');
//查找 ul 列表指定class=selected的li项
$ret = $html->find('ul li.selected');
?>
如果你觉得这样用起来麻烦,使用内置函数可以轻松定位元素的父元素、子元素与相邻元素
// 返回父元素
$e->parent;
// 返回子元素数组
$e->children;
// 通过索引号返回指定子元素
$e->children(0);
// 返回第一个资源速
$e->first_child ();
// 返回最后一个子元素
$e->last _child ();
// 返回上一个相邻元素
$e->prev_sibling ();
//返回下一个相邻元素
$e->next_sibling ();
?>
元素属性操作
使用简单的正则表达式来操作属性选择器。
[attribute] – 选择包含某属性的html元素
[attribute=value] – 选择所有指定值属性的html元素
[attribute!=value]- 选择所有非指定值属性的html元素
[attribute^=value] -选择所有指定值开头属性的html元素
[attribute$=value] 选择所有指定值结尾属性的html元素
[attribute*=value] -选择所有包含指定值属性的html元素
在解析器中调用元素属性
在DOM中元素属性也是对象:
// 本例中将$a的锚链接值赋给$link变量
$link = $a->href;
?>
或者:
$link = $html->find('a',0)->href;
?
每个对象都有4个基本对象属性:
tag – 返回html标签名
innertext – 返回innerHTML
outertext – 返回outerHTML
plaintext – 返回html标签中的文本
在解析器中编辑元素
编辑元素属性的用法和调用它们是类似的:
//给$a的锚链接赋新值
$a->href = 'http://www.jb51.net';
// 删除锚链接
$a->href = null;
// 检测是否存在锚链接
if(isset($a->href)) {
//代码
}
?>
解析器中没有专门的方法来添加、删除元素,不过可以变通一下使用:
// 封装元素
$e->outertext = '
// 删除元素
$e->outertext = '';
// 添加元素
$e->outertext = $e->outertext . '
// 插入元素
$e->outertext = '
?>
保存修改后的html DOM文档也非常简单:
$doc = $html;
// 输出
echo $doc;
?>
如何避免解析器消耗过多内存
在本文的开篇中,笔者就提到了Simple HTML DOM解析器消耗内存过多的问题。
如果php脚本占用内存太多,会导致网站停止响应等一系列严重的问题。解决的方法也很简单,
在解析器加载html文档并使用完成后,记得清理掉这个对象就可以了。当然,也不要把问题看
得太严重了。如果只是加载了2、3个文档,清理或不清理是没有多大区别的。当你加载了5个10
个甚至更多的文档的时候,用完一个就清理一下内存
$html->clear();
?>
一个实例:
简单范例
include "simple_html_dom.php" ;//加载simple_html_dom.php文件
$html = file_get_html('http://www.google.com/');//获取html
$dom = new simple_html_dom(); //new simple_html_dom对象
$dom->load($html) //加载html
// Find all images
foreach($dom->find('img') as $element) {
//获取img标签数组
echo $element->src . '
'; //获取每个img标签中的src
}
// Find all links
foreach($dom->find('a') as $element){ //获取a标签的数组
echo $element->href . '
';//获取每个a标签中的href
}
$html = file_get_html('http://slashdot.org/'); //获取html
$dom = new simple_html_dom(); //new simple_html_dom对象
$dom->load($html); //加载html
// Find all article blocks
foreach($dom->find('div.article') as $article) {
$item['title'] = $article->find('div.title', 0)->plaintext; //plaintext 获取纯文本
$item['intro'] = $article->find('div.intro', 0)->plaintext;
$item['details'] = $article->find('div.details', 0)->plaintext;
$articles[] = $item;
}
print_r($articles);
// Create DOM from string
$html = str_get_html('
$dom = new simple_html_dom(); //new simple_html_dom对象
$dom->load($html); //加载html
$dom->find('div', 1)->class = 'bar'; //class = 赋值 给第二个div的class赋值
$dom->find('div[id=hello]', 0)->innertext = 'foo'; //innertext内部文本
echo $dom;
//Output:
DOM methods & properties
Name Description
void __construct ( [string $filename] ) 构造函数,将文件名参数将自动加载内容,无论是文本或文件/ url。
string plaintext 纯文本
void clear () 清理内存
void load ( string $content ) 加载内容
string save ( [string $filename] ) Dumps the internal DOM tree back into a string. If the $filename is set, result string will save to file.
void load_file ( string $filename ) Load contents from a from a file or a URL.
void set_callback ( string $function_name ) 设置一个回调函数。
mixed find ( string $selector [, int $index] ) 找到元素的CSS选择器。返回第n个元素对象如果索引设置,否则返回一个数组对象。
4.find 方法详细介绍
find ( string $selector [, int $index] )
// Find all anchors, returns a array of element objects a标签数组
$ret = $html->find('a');
// Find (N)th anchor, returns element object or null if not found (zero based)第一个a标签
$ret = $html->find('a', 0);
// Find lastest anchor, returns element object or null if not found (zero based)最后一个a标签
$ret = $html->find('a', -1);
// Find all
$ret = $html->find('div[id]');
// Find all
$ret = $html->find('div[id=foo]');
// Find all element which id=foo
$ret = $html->find('#foo');
// Find all element which class=foo
$ret = $html->find('.foo');
// Find all element has attribute id
$ret = $html->find('*[id]');
// Find all anchors and images a标签与img标签数组
$ret = $html->find('a, img');
// Find all anchors and images with the "title" attribute
$ret = $html->find('a[title], img[title]');
// Find all
in$es = $html->find('ul li'); ul标签下的li标签数组
// Find Nested
$es = $html->find('div div div'); div标签下div标签下div标签数组
// Find all
in$es = $html->find('table.hello td'); table标签下td标签数组
// Find all td tags with attribite align=center in table tags
$es = $html->find('table td[align=center]');
5.Element 的方法
$e = $html->find("div", 0); //$e 所拥有的方法如下表所示
Attribute Name Usage
$e->tag 标签
$e->outertext 外文本
$e->innertext 内文本
$e->plaintext 纯文本
// Example
$html = str_get_html("
echo $e->tag; // Returns: " div"
echo $e->outertext; // Returns: "
echo $e->innertext; // Returns: " foo bar"
echo $e->plaintext; // Returns: " foo bar"
6.DOM traversing 方法
Method Description
mixed$e->children ( [int $index] ) 子元素
element$e->parent () 父元素
element$e->first_child () 第一个子元素
element$e->last_child () 最后一个子元素
element$e->next_sibling () 后一个兄弟元素
element$e->prev_sibling () 前一个兄弟元素
// 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');
```
一键复制
编辑
Web IDE
原始数据
按行查看
历史