Friday, 14 December 2012

PHP - XML: Replacing Node

PHP XML Tips - Part 9: Do you want to replace a node in XML? You can use replaceChild() like 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    $id     = $xml->createElement("id");
24    $idText = $xml->createTextNode("3");
25    $id->appendChild($idText);
26   
27    $title     = $xml->createElement("title");
28    $titleText = $xml->createTextNode("PHP Framework");
29    $title->appendChild($titleText);
30   
31    $author     = $xml->createElement("author");
32    $authorText = $xml->createTextNode("Reza Christian");
33    $author->appendChild($authorText);
34   
35    $book   = $xml->createElement("book");
36    $book->appendChild($id);
37    $book->appendChild($title);
38    $book->appendChild($author);
39   
40    $fnode->replaceChild($book,$ori);
41   
42    echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
43    ?>

Books.xml, you can see at this.

Result, like this


No comments:

Post a Comment