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: $dom=new DOMDocument('1.0','iso-8859-1'); $rootElement=$dom->createElement('rootnode',''); $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 $dom->appendChild($rootElement); $rootElement->appendChild($secondElement); $rootElement->appendChild($thirdElement); // tell the browser the output is XML via the 'Content-Type' HTTP header header('Content-Type: text/xml'); // display DOM document echo $dom->saveXML(); /* displays the following <?xml version="1.0" encoding="iso-8859-1"?> <rootnode> <secondnode>This is the second element of the new DOM document</secondnode> <thirdnode>This is the third element of the new DOM document</thirdnode> </rootnode> */ 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? At this moment, and with these two examples still spinning in your mind, you may have noticed the remarkable similarity between the DOM XML API and the one used when working with JavaScript, which can facilitate learning how to perform basic tasks on XML documents with this PHP extension. 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 |
|
|
|
|
|
|
|