Solved

Read DOM Document then Delete the node

Posted on 2008-10-15
6
1,347 Views
Last Modified: 2013-12-13
I am using PHP.
I am reading an XML document using DOMDocument, I run through a foreach to loop through nodes.  After I read an element node, pull out all of its children... I then need to remove that node from the xml file.

Any one have examples as to how to accomplish this.  I seem to read it in ok.  I am having a hard time deleting the node i just read, then saving the xml file, wash... rinse... repeat through the entire xml file.

Any help is appreciated.

Thanks
0
Comment
Question by:jrlitm
  • 3
  • 3
6 Comments
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22725543
You should use remove_child(), there is an example here:

http://php.net/manual/en/function.domnode-remove-child.php
0
 

Author Comment

by:jrlitm
ID: 22733145
I see the example.  However I am not quite getting it to fit into place.

In the attached example I have the data I need.  Now I need to clear this out or delete this node before I go onto the next node.

Ideas?

Thanks


$xmlfile =  'external/external_post.xml';

$doc = new DOMDocument();

$doc->load( $xmlfile );
 

$issues = $doc->getElementsByTagName( "issue" );

foreach( $issues as $issue )

{
 

$issue_titles= $issue->getElementsByTagName( "issue_title" );

$issue_title= $issue_titles->item(0)->nodeValue;
 

$issues = $issue->getElementsByTagName( "issue" );

$issue = $issues->item(0)->nodeValue;
 

}

Open in new window

0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 22735230
First, there is something strange in the code you posted. You create a list in line 5, and loop through it, starting at line 6. This loop includes lines 12 and 13, where you re-assign $issues, the variable you are looping trough, and $issue, the variable php is re-creating in line 6 for each iteration of the loop... just remove those two lines (12 & 13).

You can not update an xml file directly, as if it was a database. It is possible to update an xml file, but it is not practical. It is much easier to create a new file with the needed modification, in this case without the nodes you do not want.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 

Author Comment

by:jrlitm
ID: 22790588
Hi CXR,

Ok I am close to figuring this out:

xml File:
<issues>
  <issue acc_num="23452345">
    <issue_title>Title</issue_title>
    <issue_desc>Descriptions</issue_desc>
  </issue>
 <issue acc_num="23433345">
    <issue_title>Title</issue_title>
    <issue_desc>Descriptions</issue_desc>
  </issue>
 <issue acc_num="23333345">
    <issue_title>Title</issue_title>
    <issue_desc>Descriptions</issue_desc>
  </issue>
</issues>


The code snippet seems to go through and remove all the children under <issues> except for the last one.  It always leaves one behind.

Any ideas as to why it is not finishing.

Thanks
   function Xml_Dataclear(){

        $xmlfile =  'external/external_post.xml';   

        $dom=new DOMDocument;

        $dom->formatOutput = true;

        $dom->preserveWhiteSpace = false;

        $dom->validateOnParse = true;

        $dom->load($xmlfile);

        //$dom->loadXML($xmlfile);
 

       foreach($issues as $key => $issue){

            while($issue->hasChildNodes()){

                $issue->removeChild($issue->childNodes->item(0));

            }

            $issue->parentNode->removeChild($issue);  

        } 

        while($issue->hasChildNodes()){

        $issue->removeChild($issue->childNodes->item(0));

        }

        $issue->parentNode->removeChild($issue);      

       $dom->save($xmlfile) or die ("Error saving to file");

       

   }

Open in new window

0
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 125 total points
ID: 22791730
There are some problems related to using foreach() with a DOMNodeList object. This is a "live" sequence object, deleting an item at the start changes the index for all following items. Looping backwards eliminates this problem.
   function Xml_Dataclear($xmlfile) {

     $dom=new DOMDocument;

     $dom->formatOutput = true;

     $dom->preserveWhiteSpace = false;

     $dom->validateOnParse = true;

     $dom->load($xmlfile);

     $issues = $dom->getElementsByTagName("issue");

     for($i=$issues->length-1;$i>=0;$i--) {

       $issue = $issues->item($i);

       while($issue->hasChildNodes())

         $issue->removeChild($issue->childNodes->item(0));

       $issue->parentNode->removeChild($issue);  

     }

     $dom->save($xmlfile) or die("Error saving to file");

   }

Open in new window

0
 

Author Comment

by:jrlitm
ID: 22796608
Ok just to recap for anyone that is interested.  

With Cxr's gentle proding... I have fixed this.  I had to resolve this issue with two read processes.  I am sure there is an easier way... but this seemed to work for me.

This app runs in batch mode.  A data form updates an xml file, and in regular intervals a cron event runs this script to post the data into the database.

The script:
I read the data in.  Processed the data.  Verified it processed correctly, then remove the data at the end.

For some reason reading an element, processing then removing that element before reading the next element caused me sleepless nights.  I think Cxr was trying to tell me that it would cause me difficulty, but I was too stubborn to let it sink in.

The last post from Cxr finished the script.  It worked perfectly and is a very important issue with DOMNodeList.  

This is complete.  Thank you Cxr for your help!!!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

864 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now