Dynamic XML document construction with the PHP DOM
Adding elements and text nodes
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.
There are two steps to the process:
- 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.
- 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
<?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();
?>
// save and display treeecho $dom->saveXML();?>Here, I’ve first created a root element named and attached it to the XML header. Next, I’ve created an element named and attached it to the root element. And finally, I’ve created a text node with the value “pepperoni” and attached it to the element. The result should look like this:
<?xml version=”1.0″?>
<toppings>
<item>pepperoni</item>
</toppings>
