PHP XML Tips - Part 7: Do you want add nodes to exist XML? Ok, I will show to you. Look at this example:
<?php
$file = "books.xml";
$fp = fopen($file, "rb") or die("cannot open file");
$str = fread($fp, filesize($file));
$xml = new DOMDocument();
$xml->formatOutput = true;
$xml->preserveWhiteSpace = false;
$xml->loadXML($str) or die("Error");
// original
echo "<xmp>OLD:\n". $xml->saveXML() ."</xmp>";
// get document element
$root = $xml->documentElement;
$fnode = $root->firstChild;
//add a node
$ori = $fnode->childNodes->item(2);
$id = $xml->createElement("id");
$idText = $xml->createTextNode("3");
$id->appendChild($idText);
$title = $xml->createElement("title");
$titleText = $xml->createTextNode("PHP Framework");
$title->appendChild($titleText);
$author = $xml->createElement("author");
$authorText = $xml->createTextNode("Reza Christian");
$author->appendChild($authorText);
$book = $xml->createElement("book");
$book->appendChild($id);
$book->appendChild($title);
$book->appendChild($author);
$fnode->insertBefore($book,$ori);
echo "<xmp>NEW:\n". $xml->saveXML() ."</xmp>";
?>
First, you must have a xml document named "books.xml". You can see at this.
After run it, you may get like this: