加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

用php解析html的实现代码

发布时间:2020-12-13 05:58:33 所属栏目:PHP教程 来源:网络整理
导读:最近想用php写一个爬虫,就需要解析html,在sourceforge上找到一个项目叫做PHP Simple HTML DOM Parser,它可以以类似jQuery的方式通过css选择器来返回指定的DOM元素,功能十分强大。 首先要在程序的开始引入simple_html_dom.php这个文件 div class="codetit

最近想用php写一个爬虫,就需要解析html,在sourceforge上找到一个项目叫做PHP Simple HTML DOM Parser,它可以以类似jQuery的方式通过css选择器来返回指定的DOM元素,功能十分强大。
首先要在程序的开始引入simple_html_dom.php这个文件
<div class="codetitle"><a style="CURSOR: pointer" data="75918" class="copybut" id="copybut75918" onclick="doCopy('code75918')"> 代码如下:<div class="codebody" id="code75918">
include_once('simple_html_dom.php');

PHP Simple HTML DOM Parser提供了3种方式来创建DOM对象
<div class="codetitle"><a style="CURSOR: pointer" data="67632" class="copybut" id="copybut67632" onclick="doCopy('code67632')"> 代码如下:<div class="codebody" id="code67632">
// 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');

得到DOM对象后就可以进行各种操作了
<div class="codetitle"><a style="CURSOR: pointer" data="45605" class="copybut" id="copybut45605" onclick="doCopy('code45605')"> 代码如下:<div class="codebody" id="code45605">
// 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,-1);
// Find all

with the id attribute
$ret = $html->find('div[id]');
// Find all
which attribute id=foo
$ret = $html->find('div[id=foo]');

这里可以使用各种css选择器,就像在jQuery中进行DOM操作一样,非常方便。此外,还有两个特殊的属性可以得到文本和注释的内容
<div class="codetitle"><a style="CURSOR: pointer" data="85126" class="copybut" id="copybut85126" onclick="doCopy('code85126')"> 代码如下:
<div class="codebody" id="code85126">
// Find all text blocks
$es = $html->find('text');
// Find all comment () blocks
$es = $html->find('comment');

当然,还是类似于jQuery,PHP Simple HTML DOM Parser也支持链式操作,以及各种访问DOM元素的简单方法
<div class="codetitle"><a style="CURSOR: pointer" data="66564" class="copybut" id="copybut66564" onclick="doCopy('code66564')"> 代码如下:<div class="codebody" id="code66564">
// 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');

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读