Friday, 14 December 2012

PHP - XML: Adding XML Nodes

PHP XML Tips - Part 7: Do you want add nodes to exist XML? Ok, I will show to you. Look at this example:
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    //add a node
21    $ori    = $fnode->childNodes->item(2);
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->insertBefore($book,$ori);
41   
42    echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
43    ?>

First, you must have a xml document named "books.xml". You can see at this.

After run it, you may get like this:
XML - add nodes
XML - add nodes

No comments:

Post a Comment