Reputation: 309
Okay here is a very common xml parsing method, getting child nodes, but it's just not working how it should for me...
I CANNOT get an array of childNodes from my root element here, but I can get it from any other node when they have children, that's not a problem. It's whenever I encounter getting childnodes from this document element that I can't seem to get more than just the very first child.
I need to get all the first level nodes from document element..
$xdoc=createDOMDocument($file);
$all_children= $xdoc->documentElement->childNodes;
echo count($all_children);
function createDOMDocument($file){
$xdoc = new DOMDocument();
$xdoc->formatOutput = true;
$xdoc->preserveWhiteSpace = false;
$xdoc->load($file);
return $xdoc;
}
But this will only ever output "1", it doesn't find all the nodes, it always stops at the first node when I'm trying to output it. This makes no sense to me.
The only node it ever finds below is:
<title>some title</title>
If I delete that node, it will find topicmeta and so on, but never every node into an array which is what I need.
Here's the XML:
<?xml version="1.0" encoding="UTF-8"?>
<map title="mytitle" xml:lang="en-us">
<title>some title</title>
<topicmeta>
<prodinfo>
<prodname>a product</prodname>
<vrmlist>
<vrm version="8.5"/>
</vrmlist>
<platform/>
</prodinfo>
</topicmeta>
<topichead navtitle="cat1" id="topichead4f53aeb751c875.38130575">
<topichead navtitle="another topic"/>
</topichead>
<topichead navtitle="cat2" id="topichead4f53aeb3596990.18552413"/>
<topichead navtitle="cat3" id="topichead4f52fd157487f9.21599660"/>
</map>
Upvotes: 3
Views: 22801
Reputation: 191
This works for me ...
$xml = new DOMDocument();
$xml->load('read.xml');
$root = $xml->documentElement;
foreach($root->childNodes as $node){
print $node->nodeName.' - '.$node->nodeValue;
}
I did have to change <topichead navtitle="cat3" id="topichead4f52fd157487f9.21599660">
to <topichead navtitle="cat3" id="topichead4f52fd157487f9.21599660" />
Upvotes: 10
Reputation: 3319
Despite the things I mentioned in my comment, I think I understand what you're trying to do.
The thing here is that count()
isn't going to work. I'm not sure if it's a limitation of the Traversable interface it uses or if a quirk of the DOM class in general.
What you're looking for is:
$all_children = $xdoc->documentElement->childNodes;
echo $all_children->length;
Using ->childNodes
returns a DOMNodeList. When in doubt, you can get_class()
your variables to see what type of object it is, then look it up on php.net. :)
Upvotes: 3