问题描述
我正在使用,我正在尝试获取具有给定类名称的DOM节点内的元素。获取该子元素的最佳方式是什么?
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?
更新:我最终使用 Mechanize
for PHP更容易使用。
Update: I ended up using Mechanize
for PHP which was much easier to work with.
推荐答案
更新:Xpath版本的 * [@ class〜='my-class']
css selector
Update: Xpath version of *[@class~='my-class']
css selector
所以在我的评论下面回应hakre的评论我很好奇,并研究了 Zend_Dom_Query
之后的代码。看起来上面的选择器被编译到以下xpath(未经测试):
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')]
所以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
的实例。
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
.
使用xpath选择器?
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.
如果您需要使用非常复杂的选择器做很多,我会推荐,它支持CSS选择器语法jQuery):
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\"]");
这篇关于通过classname获取DOM元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!