DOMDocument需要搜索属性class =“something”的元素

时间:2010-08-09 20:00:13

标签: php domdocument

在PHP中,我使用的是DOMDocument,我需要搜索属性为class =“something”的元素

我是DOMDocument的新手(我一生都在使用REGEX,所以请帮助我:P)

好的,我的问题是,我发现了一个使用getElementById的DOMElement,现在我想查看这个元素的子元素并检索一个有特定类的节点,class =“something”

我该怎么做?

2 个答案:

答案 0 :(得分:3)

使用XPath查询:

$xpath = new DOMXPath($document);
// keep the quotes around the classname
$elementsThatHaveMyClass = $xpath->query('//*[@class="class here"]');

表达式意味着“从文档中的任何位置,找到class属性等于class here”的任何标记。您可以阅读有关XPath语法here的更多信息。

答案 1 :(得分:3)

对于您希望按类过滤的文档DOMNode $n $d,您可以执行此操作(此搜索递归):

$xp = new DOMXpath($d);
foreach ($xp->query('//*[contains(@class, \'classname\')]', $n) as $found) {
    //do sth with $found
}

contains的要点是捕获那些类属性有多个值的节点,但它有点太粗糙了。有关更好的解决方案,请参阅here