Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Dynamic XML in PHP (http://www.go4expert.com/articles/dynamic-xml-php-t3479/)

Mary 19Mar2007 18:46

Dynamic XML in PHP
 

Creating dynamic XML with PHP



When working with XML-based applications, developers often find themselves facing the requirement to generate XML-encoded data structures on the fly. Examples of this include an XML order template based on user input in a Web form, or an XML representation of a server request or client response based on run-time parameters.

Although this task might seem intimidating, it's actually quite simple when one takes into account PHP's sophisticated DOM API for dynamic node construction and manipulation. In this article, you will get know the main functions in this API, showing you how to programmatically generate a complete well-formed XML document from scratch and save it to disk.

Note: This article assumes a working Apache/PHP5 installation with the DOM functions enabled, and a working knowledge of basic XML constructs such as elements, attributes and CDATA blocks. You can obtain an introduction to these topics from the introductory material at Melonfire (http://melonfire.com/community/colum...icle.php?id=78 and http://melonfire.com/community/colum...icle.php?id=79)

Creating the Doctype declaration



Let's start right at the top, with the XML declaration. In PHP, this is fairly simple; it only requires you to instantiate an object of the DOMDocument class and supply it with a version number. To see it in action type out the example script in Listing A.

Listing A
Code: PHP

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// save and display tree
echo $dom->saveXML();
?>

Notice the saveXML() method of the DOMDocument object -- I'll come back to this later, but for the moment simply realise that this is the method used to output a current snapshot of the XML tree, either to a file or to the browser. In this case, I've sent the output directly to the browser as ASCII text for readability purposes; in real-world applications, you would probably send this with a Content-Type: text/xml header.

When you view the output in your browser, you should see something like this:

Code: XML

<?xml version="1.0"?>

Adding elements and text nodes



Now that's all very pretty and fine, but the real power of XML comes from its elements and the content they enclose. Fortunately, once you've got the basic DOMDocument initialised, this becomes extremely simple. There are two steps to the process:

1. For each element or text node you wish to add, call the DOMDocument object's createElement() or createTextNode() method with the element name or text content. This will result in the creation of a new object corresponding to the element or text node.

2. Append the element or text node to a parent node in the XML tree by calling that node's appendChild() method and passing it the object produced in the previous step.

An example will make this clearer. Consider the script in Listing B.

Listing B
Code: PHP

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// save and display tree
echo $dom->saveXML();
?>

Here, I've first created a root element named <toppings> and attached it to the XML header. Next, I've created an element named <item> and attached it to the root element. And finally, I've created a text node with the value "pepperoni" and attached it to the <item> element. The result should look like this:

Code: XML

<?xml version="1.0"?>
<toppings>
    <item>pepperoni</item>
</toppings>

If you'd like to add another topping, simply create another <item> and populate it with different content (Listing C).

Listing C
Code: PHP

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create another text node
$text = $dom->createTextNode("tomato");
$item->appendChild($text);

// save and display tree
echo $dom->saveXML();
?>

And here's the revised output:

Code: XML

<?xml version="1.0"?>
<toppings>
    <item>pepperoni</item>
    <item>tomato</item>
</toppings>

Adding attributes



You can also add qualifying information to your elements, through the thoughtful use of attributes. With the PHP DOM API, attributes are added in a two-step process: first create an attribute node holding the name of the attribute with the DOMDocument object's createAttribute() method, and then append a text node to it holding the attribute value. Listing D is an example.

Listing D
Code: PHP

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// create attribute node
$price = $dom->createAttribute("price");
$item->appendChild($price);

// create attribute value node
$priceValue = $dom->createTextNode("4");
$price->appendChild($priceValue);

// save and display tree
echo $dom->saveXML();
?>

And here's what the output will look like:
Code: XML

<?xml version="1.0"?>
<toppings>
    <item price="4">pepperoni</item>
</toppings>

Adding CDATA blocks and processing instructions



While not used quite as often, CDATA blocks and processing instructions (PI) are also well-supported by the PHP API, through the DOMDocument object's createCDATASection() and createProcessingInstruction() methods. Listing E shows you an example.

Listing E
Code: PHP

<?php
// create doctype
$dom = new DOMDocument("1.0");

// display document in browser as plain text
// for readability purposes
header("Content-Type: text/plain");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// create attribute node
$price = $dom->createAttribute("price");
$item->appendChild($price);

// create attribute value node
$priceValue = $dom->createTextNode("4");
$price->appendChild($priceValue);

// create CDATA section
$cdata = $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n");
$root->appendChild($cdata);

// create PI
$pi = $dom->createProcessingInstruction("pizza", "bake()");
$root->appendChild($pi);

// save and display tree
echo $dom->saveXML();
?>

And here's the output:

Code: XML

<?xml version="1.0"?>
<toppings>
    <item price="4">pepperoni</item>
    <![CDATA[
    Customer requests that pizza be sliced into 16 square pieces
    ]]>

    <?pizza bake()?>
</toppings>

Saving the results



Once you've got the tree the way you want it, you can either save it to a file or store it in a PHP variable. The former function is performed by calling the save() method with a file name, while the latter is performed by calling the saveXML() method and assigning the result to a string. Here's an example (Listing F).

Listing F
Code: PHP

<?php
// create doctype
$dom = new DOMDocument("1.0");

// create root element
$root = $dom->createElement("toppings");
$dom->appendChild($root);
$dom->formatOutput=true;

// create child element
$item = $dom->createElement("item");
$root->appendChild($item);

// create text node
$text = $dom->createTextNode("pepperoni");
$item->appendChild($text);

// create attribute node
$price = $dom->createAttribute("price");
$item->appendChild($price);

// create attribute value node
$priceValue = $dom->createTextNode("4");
$price->appendChild($priceValue);

// create CDATA section
$cdata = $dom->createCDATASection("\nCustomer requests that pizza be sliced into 16 square pieces\n");
$root->appendChild($cdata);

// create PI
$pi = $dom->createProcessingInstruction("pizza", "bake()");
$root->appendChild($pi);

// save tree to file
$dom->save("order.xml");

// save tree to string
$order = $dom->save("order.xml");
?>

That's it. Hopefully you found this article interesting, and will be able to use these techniques in your daily work with XML.

abilondias 24Jan2011 09:17

Re: Dynamic XML in PHP
 
Hi,

Liked so much your article,
I have a basic knowledge on PHP, but i dont know what is the "->"

Thanks,

~abilondias

shrikrishnatech 9Feb2011 13:19

Re: Dynamic XML in PHP
 
nice explain

danieljames123 5May2011 17:10

Re: Dynamic XML in PHP
 
Thanks to share this

kumkum01 29Jul2011 12:37

Re: Dynamic XML in PHP
 
Hi.....I think it is very nice sharing in here.........thanks a lot.......:charming::charming:

tanmayk 2Feb2012 11:20

Re: Dynamic XML in PHP
 
Thank you so much...excellent post!!

Just what i needed.!

jamewhite86 3Feb2012 09:14

Re: Dynamic XML in PHP
 
it's actually quite simple when one takes into account PHP's sophisticated DOM API for dynamic node construction and manipulation. really a lot of information share in your website. thanks

Scripting 3Feb2012 23:04

Re: Dynamic XML in PHP
 
Well explained tutorial. Keep it up!


All times are GMT +5.5. The time now is 21:42.