7

我有两个 DOMNodeLists

$textNodes = $xpath->query('//text()');

$titleNodes = $xpath->query('//@title');

如何将它们合并到 DOMNodeLists 以便我可以将它与foreach循环一起使用?

4

1 回答 1

9

XPath 支持|组合两个节点集的运算符:

$textNodes = $xpath->query('//text() | //@title');

想象一下这个简单的例子:

$xml = '<?xml version="1.0"?>
<person>
  <name>joe</name>
  <age>99</age>
</person>';

$doc = new DOMDocument();
$doc->loadXml($xml);
$selector = new DOMXPath($doc);

$nodes = $selector->query('//name | //age');

foreach($nodes as $node) {
    echo $node->nodeName, PHP_EOL;
}
于 2013-01-04T22:49:16.823 回答