php html文档解析器simple_html_dom

来源:互联网 发布:.net软件开发程序员 编辑:程序博客网 时间:2024/06/10 11:38

一直以来使用php解析html文档树都是一个难题。Simple HTML DOM parser 帮我们很好地解决了这个问题。可以通过这个php类来解析html文档,对其中的html元素进行操作 (PHP5+以上版本)。

解析器不仅仅只是帮助我们验证html文档;更能解析不符合W3C标准的html文档。它使用了类似jQuery的元素选择器,通过元素的id,class,tag等等来查找定位;同时还提供添加、删除、修改文档树的功能。当然,这样一款强大的html Dom解析器也不是尽善尽美;在使用的过程中需要十分小心内存消耗的情况。不过,不要担心;本文中,笔者在最后会为各位介绍如何避免消耗过多的内存。

开始使用

上传类文件以后,有三种方式调用这个类:

从url中加载html文档

从字符串中加载html文档

从文件中加载html文档

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
// 新建一个Dom实例
$html=newsimple_html_dom();
 
// 从url中加载
$html->load_file('http://www.cnphp.info/php-simple-html-dom-parser-intro.html');
 
// 从字符串中加载
$html->load('<html><body>从字符串中加载html文档演示</body></html>');
 
//从文件中加载
$html->load_file('path/file/test.html');
?>

如果从字符串加载html文档,需要先从网络上下载。建议使用cURL来抓取html文档并加载DOM中。

查找html元素

可以使用find函数来查找html文档中的元素。返回的结果是一个包含了对象的数组。我们使用HTML DOM解析类中的函数来访问这些对象,下面给出几个示例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
 
//查找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的选择器来查找定位元素:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php
// 查找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]');
?>

解析器支持对子元素的查找

?
1
2
3
4
5
6
7
8
9
<?php
 
// 查找 ul列表中所有的li项
$ret=$html->find('ul li');
 
//查找 ul 列表指定class=selected的li项
$ret=$html->find('ul li.selected');
 
?>

如果你觉得这样用起来麻烦,使用内置函数可以轻松定位元素的父元素、子元素与相邻元素

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?php
// 返回父元素
$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中元素属性也是对象:

?
1
2
3
4
<?php
// 本例中将$a的锚链接值赋给$link变量
$link=$a->href;
?>

或者:

?
1
2
3
<?php
$link=$html->find('a',0)->href;
?>

每个对象都有4个基本对象属性:

tag – 返回html标签名

innertext – 返回innerHTML

outertext – 返回outerHTML

plaintext – 返回html标签中的文本

在解析器中编辑元素

编辑元素属性的用法和调用它们是类似的:

?
1
2
3
4
5
6
7
8
9
10
11
12
<?php
//给$a的锚链接赋新值
$a->href = 'http://www.cnphp.info';
 
// 删除锚链接
$a->href = null;
 
// 检测是否存在锚链接
if(isset($a->href)) {
//代码
}
?>

解析器中没有专门的方法来添加、删除元素,不过可以变通一下使用:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?php
 
// 封装元素
$e->outertext = '<div class="wrap">' . $e->outertext . '<div>';
 
// 删除元素
$e->outertext = '';
 
// 添加元素
$e->outertext = $e->outertext . '<div>foo<div>';
 
// 插入元素
$e->outertext = '<div>foo<div>'.$e->outertext;
?>

保存修改后的html DOM文档也非常简单:

?
1
2
3
4
5
6
<?php
$doc=$html;
 
// 输出
echo$doc;
?>

如何避免解析器消耗过多内存

在本文的开篇中,笔者就提到了Simple HTML DOM解析器消耗内存过多的问题。如果php脚本占用内存太多,会导致网站停止响应等一系列严重的问题。解决的方法也很简单,在解析器加载html文档并使用完成后,记得清理掉这个对象就可以了。当然,也不要把问题看得太严重了。如果只是加载了2、3个文档,清理或不清理是没有多大区别的。当你加载了5个10个甚至更多的文档的时候,用完一个就清理一下内存绝对是对自己负责啦^_^

?
1
2
3
<?php
$html->clear();
?>

[php] view plaincopy
  1. <p>简单范例  
  2. <?php                                            include "simple_html_dom.php" ;    //加载simple_html_dom.php文件  
  3.     $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 . '<br>';    //获取每个img标签中的src                               }                                                       // Find all links                                               foreach($dom->find('a'as $element){    //获取a标签的数组                                         echo $element->href . '<br>';    //获取每个a标签中的href                               }</p><p>  
  4.     $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);</p><p> }</p><p>  
  5.     // Create DOM from string</p><p>    $html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');  
  6.     $dom = new simple_html_dom();     //new simple_html_dom对象</p><p>    $dom->load($html);      //加载html  
  7.     $dom->find('div', 1)->class = 'bar';    //class = 赋值 给第二个div的class赋值</p><p>   $dom->find('div[id=hello]', 0)->innertext = 'foo';   //innertext内部文本</p><p>    echo $dom; </p><p>  // Output: <div id="hello">foo</div><div id="world" class="bar">World</div></p><p> </p><p> DOM methods & properties   
  8.     Name Description   
  9.     void __construct ( [string $filename] ) 构造函数,将文件名参数将自动加载内容,无论是文本或文件/ url。   
  10.    string plaintext 纯文本   
  11.     void clear () 清理内存   
  12.     void load ( string $content ) 加载内容   
  13.     string save ( [string $filename] ) Dumps the internal DOM tree back into a string. If the $filename is set, result string   will save to file.   
  14.     void load_file ( string $filename ) Load contents from a from a file or a URL.   
  15.     void set_callback ( string $function_name ) 设置一个回调函数。   
  16.     mixed find ( string $selector [, int $index] ) 找到元素的CSS选择器。返回第n个元素对象如果索引设置,否则返回一个数组对象。 </p><p>   
  17.     4.find 方法详细介绍</p><p>  
  18.     find ( string $selector [, int $index] )   
  19.     // Find all anchors, returns a array of element objects a标签数组  
  20.     $ret = $html->find('a');</p><p>  // Find (N)th anchor, returns element object or null if not found (zero based)第一个a标签  
  21.     $ret = $html->find('a', 0);</p><p>   // Find lastest anchor, returns element object or null if not found (zero based)最后一个a标签  
  22.     $ret = $html->find('a', -1); </p><p> // Find all <div> with the id attribute   
  23.     $ret = $html->find('div[id]');</p><p>    // Find all <div> which attribute id=foo  
  24.     $ret = $html->find('div[id=foo]'); </p><p>  
  25.     // Find all element which id=foo  
  26.     $ret = $html->find('#foo');</p><p>   // Find all element which class=foo  
  27.     $ret = $html->find('.foo');</p><p>   // Find all element has attribute id  
  28.     $ret = $html->find('*[id]'); </p><p> // Find all anchors and images a标签与img标签数组   
  29.     $ret = $html->find('a, img');  </p><p>  // Find all anchors and images with the "title" attribute  
  30.     $ret = $html->find('a[title], img[title]');</p><p>  
  31.     // Find all <li> in <ul>   
  32.     $es = $html->find('ul li'); ul标签下的li标签数组</p><p>  // Find Nested <div> tags  
  33.     $es = $html->find('div div div');  div标签下div标签下div标签数组</p><p>   // Find all <td> in <table> which class=hello   
  34.     $es = $html->find('table.hello td'); table标签下td标签数组</p><p>   // Find all td tags with attribite align=center in table tags   
  35.     $es = $html->find(''table td[align=center]'); </p><p>   
  36.     5.Element  的方法  
  37.     $e = $html->find("div", 0);                              //$e 所拥有的方法如下表所示  
  38.     Attribute Name Usage   
  39.     $e->tag 标签   
  40.     $e->outertext 外文本   
  41.     $e->innertext 内文本   
  42.     $e->plaintext 纯文本 </p><p> </p><p>   // Example  
  43.     $html = str_get_html("<div>foo <b>bar</b></div>");   
  44.     echo $e->tag; // Returns: " div"  
  45.     echo $e->outertext; // Returns: " <div>foo <b>bar</b></div>"  
  46.     echo $e->innertext; // Returns: " foo <b>bar</b>"  
  47.     echo $e->plaintext; // Returns: " foo bar"</p><p>  
  48.     6.DOM traversing 方法  
  49.     Method Description   
  50.     mixed$e->children ( [int $index] ) 子元素   
  51.     element$e->parent () 父元素   
  52.     element$e->first_child () 第一个子元素   
  53.     element$e->last_child () 最后一个子元素   
  54.     element$e->next_sibling () 后一个兄弟元素   
  55.     element$e->prev_sibling () 前一个兄弟元素 </p><p>  
  56.     // Example  
  57.     echo $html->find("#div1", 0)->children(1)->children(1)->children(2)->id;  
  58.     // or   
  59.     echo $html->getElementById("div1")->childNodes(1)->childNodes(1)->childNodes(2)->getAttribute('id');  
  60. </p>  

原创粉丝点击