用php解析html的实现代码

yipeiwu_com5年前PHP代码库
最近想用php写一个爬虫,就需要解析html,在sourceforge上找到一个项目叫做PHP Simple HTML DOM Parser,它可以以类似jQuery的方式通过css选择器来返回指定的DOM元素,功能十分强大。
首先要在程序的开始引入simple_html_dom.php这个文件
复制代码 代码如下:

include_once('simple_html_dom.php');

PHP Simple HTML DOM Parser提供了3种方式来创建DOM对象
复制代码 代码如下:

// Create a DOM object from a string
$html = str_get_html('<html><body>Hello!</body></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');

得到DOM对象后就可以进行各种操作了
复制代码 代码如下:

// Find all anchors, returns a 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 <div> which attribute id=foo
$ret = $html->find('div[id=foo]');

这里可以使用各种css选择器,就像在jQuery中进行DOM操作一样,非常方便。此外,还有两个特殊的属性可以得到文本和注释的内容
复制代码 代码如下:

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

当然,还是类似于jQuery,PHP Simple HTML DOM Parser也支持链式操作,以及各种访问DOM元素的简单方法
复制代码 代码如下:

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

相关文章

php图像处理函数大全(推荐收藏)

一、创建图片资源imagecreatetruecolor(width,height);imagecreatefromgif(图片名称);imagecreatefrompng(图片名称);...

用PHP伪造referer突破网盘禁止外连的代码

比如我放纳米盘里的文件http://img.namipan.com/downfile/da333ee178bdad6531d1ec1540cf86277c116b6300887600/0...

php GD绘制24小时柱状图

80,250,430,134,35,60,233,90,263,225,120,59,151,677,340,221,550,300,229,97,230,123,133,87 ...

PHP操作Memcache实例介绍

PHP操作Memcache实例介绍

b/s: 基于浏览器和服务器架构 web程序 c/s: QQ SVN client客户端+ 服务器简单的基于文本行的协议: redis memcache 区别: 都是存储数据的,memc...

redis查看连接数及php模拟并发创建redis连接的方法

max_redis.php <?php set_time_limit (0); for($i=1;$i<=1050;$i++){ exec("nohup p...