Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get children of document element through php domdocument parser

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>
like image 706
Kayla Avatar asked May 04 '26 01:05

Kayla


1 Answers

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" />

like image 64
S Morgan Avatar answered May 05 '26 17:05

S Morgan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!