The first thing that I’m going to show you concerning the use of the DOM XML extension with PHP 5 is pretty basic. It consists of building an XML document from scratch, adding a root element to it, and finally outputting this raw data on the browser.
The following script performs all of the tasks described above, so analyze its definition in detail:
$element=$dom->createElement('testnode','This is the root element of the new DOM document');
// insert the new element as root (child of the document)
// tell the browser the output is XML via the 'Content-Type' HTTP header
// display DOM document
/* displays the following
<?xml version="1.0" encoding="iso-8859-1"?>
<testnode>This is the root element of the new DOM document</testnode>
Now that you have taken a close look at the previous script, it’s time to dissect it into separate parts and see what it does. First a new, empty DOM document is created through an instance of the “DOMDocument” class, which as you’ll see in subsequent examples, will always be the starting point for building XML documents.
Then a root element is created with the pertinent “createElement()” method and inserted into the document via another one, called “appendChild(),” which comes in handy when appending new elements to an existing document tree. In the end, these recently added contents are printed to the browser by using the “saveXML()” method. This method's function is simply to return the XML data just created to client code. Quite simple to understand, right?
At this point, you've learned how to build a simple XML document, which only contains a root element, from scratch. It’s clear to see in the previous example how the DOM API is utilized. For instance, it can be used to append new nodes to a given XML document via the "createElement()/appendChild()” methods used in tandem. As you saw in the prior example, the first method takes up two primary arguments: one is the name of the node to be created, while the other is its respective text value (or in other words, its text node).
However, I’m only scratching the surface when it comes to exploring the methods provided by the DOM XML extension, which means that there is still a long way ahead of us. Therefore, in the upcoming section, I’m going to show you how to add multiple nodes to an XML document.
Want to see how this will be done? Click on the link below and keep reading.
blog comments powered by Disqus