Friday, 14 December 2012

PHP - XML: Removing Node

PHP XML Tips - Part 8: Do you want to remove child from exist XML? You can use removeChild(). Look at this:
01    <?php
02    $file = "books.xml";
03    $fp = fopen($file, "rb") or die("cannot open file");
04    $str = fread($fp, filesize($file));
05   
06   
07           
08    $xml = new DOMDocument();
09    $xml->formatOutput = true;
10    $xml->preserveWhiteSpace = false;
11    $xml->loadXML($str) or die("Error");
12   
13    // original
14    echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
15   
16    // get document element
17    $root   = $xml->documentElement;
18    $fnode  = $root->firstChild;
19   
20    //get a node
21    $ori    = $fnode->childNodes->item(1);
22   
23    // remove
24    $fnode->removeChild($ori);
25   
26    echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
27    ?>

Books.xml, you can see at this.

Result, like this:

No comments:

Post a Comment