用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设计模式 php实现工厂模式(factory)

学习php设计模式 php实现工厂模式(factory)

一、意图 定义一个用于创建对象的接口,让子类决定实例化哪一个类。Factory Method使用一个类的实例化延迟到其子类【GOF95】 二、工厂模式结构图 三、工厂模式中主要角色...

PHP中include与require使用方法区别详解

在PHP变成中,include()与require()的功能相同,include(include_once) 与 require(require_once)都是把把包含的文件代码读入到指...

汇总PHPmailer群发Gmail的常见问题

大家在PHPmailer群发Gmail时会遇到许多常见问题,下面为大家总结了一些常见问题,希望对大家的学习有所帮助。 1.Could not authenticate 首先,如果你没有使...

php 使用redis锁限制并发访问类示例

本文介绍了php 使用redis锁限制并发访问类,并详细的介绍了并发访问限制方法。 1.并发访问限制问题 对于一些需要限制同一个用户并发访问的场景,如果用户并发请求多次,而服务器处理...

mac下使用brew配置环境的步骤分享

首先 开启web共享。 配置 httpd.conf 加入php拓展 /etc/apache2/httpd.conf 如出现 ULIMIT_MAX_FILES="ulimit -S -n...