Use PHP's DOM extension to create a DOM tree and append nodes to it:
- <?php
- // initialize DOM object
- $xml = new DOMDocument("1.0");
- // add root node <listing>
- $root = $xml->createElement("list");
- $xml->appendChild($root);
- // add element <description> to root
- $desc = $xml->createElement("description");
- $root->appendChild($desc);
- // add <description> content
- $desc->appendChild($xml->createTextNode("Sam's Shopping List"));
- // add comment
- $root->appendChild($xml->createComment("item list follows"));
- // add <item> child element
- // add quantities as attributes
- $items = $xml->createElement("items");
- $root->appendChild($items);
- $item = $xml->createElement("item");
- $items->appendChild($item);
- $item->appendChild($xml->createTextNode("eggs"));
- $item->setAttribute("units", 3);
- unset($item);
- $item = $xml->createElement("item");
- $items->appendChild($item);
- $item->appendChild($xml->createTextNode("salt"));
- $item->setAttribute("units", "100 gm");
- // add CDATA block
- $items->appendChild($xml->createCDATASection("You can't make↩
- an omelette without breaking eggs"));
- // add PI
- $root->appendChild($xml->createProcessingInstruction(↩
- "xml-dummy-pi", "shop('now')"));
- // display final tree as HTML…
- $xml->formatOutput = true;
- echo "<xmp>" . $xml->saveXML() . "</xmp>";
- // …or write it to a file as XML
- $xml->save("list.xml") or die("ERROR: Could not write to file");
- ?>
Comments
PHP's SimpleXML extension does not support node creation, so this task is better handled with PHP's DOM extension, which comes with a wide array of methods designed to help you design an XML document instance dynamically. To get started, create an instance of the DOMDocument class, and then use its createElement() method to create element objects. These element objects may then be attached to a parent node by calling the parent node object's appendChild() method. The process is illustrated in the previous listing.
Of course, an XML document is much more than just elements—which is why the DOM extension also offers createTextNode(), createCDATASection(), createProcessingInstruction(), and createComment() methods to attach text, CDATA blocks, PIs (Processing Instructions), and comments to the DOM tree respectively. Attributes for an element are set by calling the corresponding element object's setAttribute() method with appropriate parameters.
Once the tree has been generated, it may be retrieved as a string with the primary DOMDocument object's saveXML() method, or written to a file with the object's save() method.