In the previous section, you learned how to build an XML document from scratch and how to add a single root node to it. Nevertheless, this is merely a basic example of what you can do with the DOM XML extension. Now let me go one step forward and show you another practical example aimed at demonstrating how to insert multiple nodes into an existing XML document.
The corresponding code sample is as follows:
$secondElement=$dom->createElement('secondnode','This is the second element of the new DOM document');
$thirdElement=$dom->createElement('thirdnode','This is the third element of the new DOM document');
// insert the new elements into 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"?>
<secondnode>This is the second element of the new DOM document</secondnode>
<thirdnode>This is the third element of the new DOM document</thirdnode>
As shown previously, adding several nodes to an existing XML document requires using exactly the same methods that you learned in the first example. In this case, the XML document is built through the corresponding “DOMDocument” constructor and the successive elements are created and appended in that order by using the “createElement()/appendChild()” combination.
Finally, all the XML data is echoed naturally to the browser via the “saveXML()” method by sending the appropriate “Content-Type” HTTP header to the client. That was really simple to do. Don’t you think so?
Indeed I don’t want to get away from the main goal of this article. Therefore, now that you understand how to build a basic XML document as well as how to insert a few simple nodes into it, it’s time to move forward and learn how to create XML data from an existing array.
This is an interesting topic that will be discussed in detail in the next section. Thus jump ahead and keep reading.
blog comments powered by Disqus