微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

用php解析html的实现代码

最近想用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');

原文地址:https://www.jb51.cc/php/27682.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

html

相关推荐