DOMDocument需要搜索具有属性class ="something"的元素. [英] DOMDocument need to search for an element that has attribute class="something"
问题描述
在PHP中,我使用的是DOMDocument,我需要搜索一个属性为class ="something"的元素
In PHP I'm using DOMDocument and I need to search for an element that has attribute class="something"
我是DOMDocument的新手(一生都在使用REGEX,所以请帮我:P)
I'm new with DOMDocument (been using REGEX all my life so help me :P)
好吧,我的问题是,我已经使用getElementById找到了一个DOMElement,现在我想查看该元素的子元素,并检索一个具有特定类class ="something"的节点
Ok, my question is, I've found a DOMElement using getElementById, now i want to look inside the children of this element and retrieve a node that has a particular class, class="something"
我该怎么做?
推荐答案
一旦您拥有文档 $ d
的 DOMNode
$ n
您想按班级筛选谁的孩子(此搜索是递归的):
Once you have a DOMNode
$n
for a document $d
whose children you want to filter by class you can do (this searches recursively):
$xp = new DOMXpath($d);
foreach ($xp->query('//*[contains(@class, \'classname\')]', $n) as $found) {
//do sth with $found
}
包含
的目的是捕获那些其class属性具有多个值的节点,但这有点太粗糙了.有关更好的解决方案,请参见此处.
The point of contains
is to catch those nodes whose class attribute has more than one value, but it's a bit too coarse. See here for a better solution.
这篇关于DOMDocument需要搜索具有属性class ="something"的元素.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!