How to view DOMNodeList object's data in php

ahmed picture ahmed · Sep 2, 2009 · Viewed 29.4k times · Source

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?

Answer

ghbarratt picture ghbarratt · Jul 23, 2012

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.