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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With