Jump to content

how to reverse traverse xml


mpsn

Recommended Posts

Hi, starting at a given node, I want to be able to build a pathway from that current node all the way to the root node.

 

Let's say I have this email.xml file:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<email>

<message>

  <to>

  <toFirstName>Bob</toFirstName>

  <toLastName type="common">Smith</toLastName>

  </to>

</message>

</email>

 

Here is my script which btw is infinite loop:

<?php
$doc=new DOMDocument();
$doc->load("email.xml");
$pathway=array();
$dom1=$doc->getElementsByTagName("toLastName")->item(0);
while(!$dom1->documentElement->nodeName) {
$pathway[]=$dom1->nodeName."/".$dom1->parentNode->nodeName."/";
$strPathway=implode("",$pathway);
print $strPathway;
}
?>

The output I want is in this format:

email/message/to/toLastName (I will figure out how to use rsort since in the while loop it appends as: toLastName/to/message/email

 

Any help much appreciated!

Link to comment
https://forums.phpfreaks.com/topic/250540-how-to-reverse-traverse-xml/
Share on other sites

Now I realized I have no end condition so infinite loop, please see updated code again.

 

<?php
$pathway=array();
$strPathway="";
$dom1=$doc->getElementsByTagName("toLastName")->item(0);

while($dom1->parentNode!=NULL) {
$dom1=$dom1->parentNode;//NEW: update $dom1
$pathway[]=$dom1->nodeName."/".$dom1->parentNode->nodeName."/";
}
$strPathway=implode("",$pathway);
print $strPathway;
?>

So my code ALMOST works, but I get this notice. I guess the most top level is document which HAS NO PARENTS so how do I indicate that once current node is now the actual document to stop.

 

Any help much appreciated!

Notice: Trying to get property of non-object in

to/message/message/email/email/#document/#document//

As you can see above, for some reason, in browser output, it is ALMOST correct except that it is printing whatever the current node's parent, two times:

 

Notice: Trying to get property of non-object

to/message/message/email/email/#document/#document//

 

Actually it's b/c I update $dom1=$dom1->parentNode, BUT I'm still unsure as to why it is printing #document, how do I use break once I'm at the root?

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.