phpeveryday.com

The best tutorial of php, php framework, php strategies, object oriented oriented,


PHP - XML: Adding XML Nodes

Tag: xml, node   Category: PHP Basic
post: 23 Mar 2008 read: 856


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:

XML - add nodes


Series this article:
PHP - XML: Read from String
PHP - XML: Read from a File
PHP - XML: Retrieving Node Values
PHP - XML: Retrieving Attribute Values
PHP - XML: Processing XML
PHP - XML: Creating XML Document
PHP - XML: Adding XML Nodes
PHP - XML: Removing Node
PHP - XML: Replacing Node
PHP - XML: Filtering XML Nodes with XPath
PHP - XML: Filtering XML Nodes by Namespace

| Give Your Opinion | Recommend
Share and Bookmark to: These icons link to social bookmarking sites where readers can share and discover new web pages.
digg del.icio.us technorati Ma.gnolia BlinkList

Recommended articles by other readers:
Web Services: How PHP Kiss VB.NET? (Part 1)
Joomla: Fast Road to Understand Component Programming
Chart: How to Build Cool Animation Real Time Chart
Email: Send Attachement Mail
SMS : Sending SMS with PHP and ActiveXperts (Part 1)

What do You Think?
Your Name *:
Email *:
(Will not be published)
Website/URL:
Your Comment *:
* Required


624
posting