Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two DOMNodeLists in xpath

Tags:

php

xpath

I have two DOMNodeLists

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

and

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

How can I merge those to DOMNodeLists so I can use it with a foreach loop?

like image 793
Horen Avatar asked Jan 04 '13 22:01

Horen


1 Answers

XPath supports the | operator for combining two node sets:

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

Imagine this simple example :

$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;
}
like image 171
hek2mgl Avatar answered Nov 12 '22 12:11

hek2mgl