Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to view DOMNodeList object's data in php

when I want to test php array I use the following code

    print_r($myarray);

but know I want to see the data of an object my object is

    $xpath = new DOMXPath($doc);
    $myobject = $xpath->query('//*[ancestor-or-self::a]');

when I use

    print_r($myobject);

I get that output

    DOMNodeList Object ( )

I want to iterate through the values of this object to test the result of my query?

like image 805
ahmed Avatar asked Sep 02 '09 03:09

ahmed


2 Answers

DOMNodeList is an interesting object, one that you will not get much information from using print_r or var_dump.

There are many ways to view the data of a DOMNodeList object. Here is an example:

$xpath = new DOMXpath($dom);
$dom_node_list = $xpath->query($your_xpath_query);
$temp_dom = new DOMDocument();
foreach($dom_node_list as $n) $temp_dom->appendChild($temp_dom->importNode($n,true));
print_r($temp_dom->saveHTML());

(Of course use saveXML instead of saveHTML if you are dealing with XML.)

A DOMNodeList can be iterated over like an array. If you want to pull the data out of the DOMNodeList object and put it into a different data structure, such as an array or stdClass object, then you simply iterate through the "nodes" in the DOMNodeList, converting the nodes' values and/or attributes (that you want to have available) before adding them to the new data structure.

like image 132
ghbarratt Avatar answered Oct 06 '22 01:10

ghbarratt


It's possible to navigate through the nodes by using a simple foreach as follow:

foreach ($myobject as $node) {

  echo $node->nodeValue, PHP_EOL;

} // end foreach 

Hope that it can help others, the important pieces of code are the

foreach 

and the item

$node->nodeValue

for more details regarding this class please visit:

http://php.net/manual/en/class.domnodelist.php

like image 30
Danhdds Avatar answered Oct 06 '22 00:10

Danhdds