最近想用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('
mallcloud商城基于SpringBoot2.x、SpringCloud和SpringCloudAlibaba并采用前后端分离vue的企业级微服务敏捷开发系统架构。并引入组件化的思想实现高内聚低耦合,项目代码简洁注释丰富上手容易,适合学习和企业中使用。真正实现了基于RBAC、jwt和oauth2的无状态统一权限认证的解决方案,面向互联网设计同时适合B端和C端用户,支持CI/CD多环境部署,并提
// 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
$ret = $html->find('div[id]');
// find all
$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');










