按类名获取DOM元素 [英] Getting DOM elements by classname

查看:262
本文介绍了按类名获取DOM元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 PHP DOM ,我想尝试获取DOM节点中具有给定类名称的元素。

更新:我最后使用机械化
解决方案

更新:Xpath版本 * [@ class〜='my-class'] css selector



hakre的评论我很好奇,并研究了 Zend_Dom_Query 后面的代码。它看起来像上面的选择器被编译为以下xpath(未测试):



[contains(concat('',normalize-space class),''),'my-class')]



,所以php是:

  $ dom = new DomDocument(); 
$ dom-> load($ filePath);
$ finder = new DomXPath($ dom);
$ classname =my-class;
$ nodes = $ finder-> query(// * [contains(concat('',normalize-space(@class),''),'$ classname')]);

基本上我们在这里做的是规范化 class 属性,使得即使单个类也由空格限定,完整的类列表也在空格中。然后追加类,我们正在搜索一个空格。这样,我们正在有效地查找并找到 my-class 的实例。






使用xpath选择器?

  $ dom = new DomDocument 
$ dom-> load($ filePath);
$ finder = new DomXPath($ dom);
$ classname =my-class;
$ nodes = $ finder-> query(// * [contains(@class,'$ classname')]);

如果只有一种类型的元素,你可以替换 * 与特定的标记名。



如果你需要做很多这样非常复杂的选择器,我会建议 Zend_Dom_Query : p>

  $ finder = new Zend_Dom_Query($ html); 
$ classname ='my-class';
$ nodes = $ finder-> query(* [class〜= \$ classname\]);


I'm using PHP DOM and I'm trying to get an element within a DOM node that have a given class name. What's the best way to get that sub-element?

Update: I ended up using Mechanize for PHP which was much easier to work with.

解决方案

Update: Xpath version of *[@class~='my-class'] css selector

So after my comment below in response to hakre's comment i got curious and looked into the code behind Zend_Dom_Query. It looks like the above selector is compiled to the following xpath (untested):

[contains(concat(' ', normalize-space(@class), ' '), ' my-class ')]

so the php would be:

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");

Basically all we do here is normalize the class attribute so that even a single class is bounded by spaces, and the complete class list is bounded in spaces. Then append class we are searching for with a space. This way we are effectively looking for and find only instances of my-class.


Use an xpath selector?

$dom = new DomDocument();
$dom->load($filePath);
$finder = new DomXPath($dom);
$classname="my-class";
$nodes = $finder->query("//*[contains(@class, '$classname')]");

If it is only ever one type of element you can replace the * with the particular tagname.

If you need to do alot of this with very complex selector i would recommend Zend_Dom_Query which supports CSS selector syntax (a la jQuery):

$finder = new Zend_Dom_Query($html);
$classname = 'my-class';
$nodes = $finder->query("*[class~=\"$classname\"]");

这篇关于按类名获取DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆