Solved

Read DOM Document then Delete the node

Posted on 2008-10-15
6
1,344 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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Suggested Solutions

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Browsing the questions asked to the Experts of this forum, you will be amazed to see how many times people are headaching about monster regular expressions (regex) to select that specific part of some HTML or XML file they want to extract. The examp…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

757 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

19 Experts available now in Live!

Get 1:1 Help Now