simplie_html_dom类 可以通过find方法 或者类似 getElementxxxx的方式来查找一个元素。
(1),利用find方法查找元素
首先引入 simple_html_dom.php类。并实例化
$sdom = new simple_html_dom(‘http://www.baidu.com’);
$sdom->find(‘a’) 查找百度首页的所有a标签。结果返回的是一个对象数组。
查看simple_html_dom 源码可以看到 find接受三个参数$selector, $idx, $lowercase
第二个为返回结果的第几个;
找到find方法可以看到如图:
第三个参数为:是否对大小写敏感;
搜索 seek方法
第一个参数为选择器
$sdom->find(‘a’) 查找所有a标签(对象)
$sdom-find(‘a’,0) 返回第一个a标签(对象)
$sdom->find(‘a’,-1) 返回最后一个a标签(对象)
除了这种基本的查找方法,还可以用类似jquery中的
$sdom->find(‘#isDebugInfo‘); 查找所有ID为isDebugInfo的元素
$sdom->fnd(‘.isDebugInfo‘) ;查找所有class 为isDebugInfo的元素
$sdom->find(*[id]) 查找具有id属性的元素
$sdom->find(div[id=isDebugInfo]) 查找带有id为isDebugInfo的div标签
支持以下属性选择器操作:
过滤
描述
[attribute]
匹配具有指定属性的元素.
[!attribute]
匹配不具有指定属性的元素。
[attribute=value]
匹配具有指定属性值的元素
[attribute!=value]
匹配不具有指定属性值的元素
[attribute^=value]
匹配具有指定属性值开始的元素
[attribute$=value]
匹配具有指定属性值结束的元素
[attribute*=value]
匹配具有指定属性的元素,且该属性包含了一定的值
同时查找多个不同元素 $sdom->find(‘a,img’)
层级查找 $sdom->find(‘ul li’); $sdom->find(div a[class=item]);
提示:如果find的第二个参数不指定,返回的是一个键值从0开始的对象数组
(2) 用getElementby XXX 查找元素
function getElementById($id) {return $this->find(“#$id”, 0);}
function getElementsById($id, $idx=null) {return $this->find(“#$id”, $idx);}
function getElementByTagName($name) {return $this->find($name, 0);}
function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);}
还可以通过
function parentNode() {return $this->parent();}
function childNodes($idx=-1) {return $this->children($idx);}
function firstChild() {return $this->first_child();}
function lastChild() {return $this->last_child();}
function nextSibling() {return $this->next_sibling();}
function previousSibling() {return $this->prev_sibling();}
来查找它的父元素 子元素 兄弟元素
资源下载:https://github.com/samacs/simple_html_dom
最后编辑:2014-09-17作者:开心乐窝