Login

A Quick Overview of the XML DOM Extension in PHP 5

To be frank, how many times in your life as a PHP developer have you had to deal with XML documents? Probably dozens of times, particularly if you use it to develop PHP applications that implement some kind of web service, or possibly when creating RSS feeds and template files for different web sites. And, surely, the list goes on and on.

But wait a minute! Of course, I’m not saying that XML is the evil player of this game, because you’d be completely misunderstanding my point. XML is great for different reasons, which are definitely out of the scope of this article. But when you need to build large XML documents from scratch or even parse them in some way, you can be faced with a quite challenging and time-consuming process that might cause hair loss!

However, as you know, PHP 5 comes equipped with a number of extensions that will make your life much easier when it comes to building and parsing things like XML data. For example, there’s the “SimpleXML” library, which permits you to perform some useful tasks, such as reading XML data from files and strings, iterating over XML documents, parsing individual nodes, and so forth.

PHP 5 has yet another extension that can be really helpful for handling XML data in all sorts of clever ways. In this case, I’m talking about the one called “XML DOM.” If you’ve already worked with it during the development of your PHP 5 applications, then you should be well aware of its strong capabilities when it comes to dealing with XML data.

Of course, there’s the possibility that aside from being a PHP programmer, you’re also a professional diver, who spends most of your time exploring the beauty of the oceans and, in consequence, you’ve never heard about this PHP extension. In that case, let me tell you a couple of interesting things that you can do with it.

Simply put, the DOM XML extension, as its name suggests, will permit you to work on XML documents by way of the DOM API. In this way, it allows you to read from and write to XML files, build XML data from scratch and parse specific nodes, extract them as an array, and even process HTML markup in different ways by using a handful of intuitive methods that closely resemble the ones used with JavaScript.

As you can see, this PHP extension offers a bunch of powerful features that can be useful for working with XML data. Therefore, provided that you’re interested in learning how to get started using it within your own PHP applications, in this article series I’ll be discussing some of its most relevant methods and properties and accompanying all of these explanations with concise and instructive hands-on examples.

Does this sound good to you? Let’s get started right now!

{mospagebreak title=Building XML documents from scratch}

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:

$dom=new DOMDocument(‘1.0′,’iso-8859-1’);

$element=$dom->createElement(‘testnode’,’This is the root element of the new DOM document’);

// insert the new element as root (child of the document)

$dom->appendChild($element);

// 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"?>

<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).

Having demonstrated how to construct a basic XML document with the DOM XML PHP extension, I’m pretty sure that you’ll find numerous similarities when working with the DOM and JavaScript, since you can also create new elements, copy and remove new nodes from the web document tree, and so forth.

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.

{mospagebreak title=Adding multiple nodes to an XML document}

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.

{mospagebreak title=Adding nodes to a simple XML document by using array elements}

As you saw in the prior section, inserting a few basic nodes into a recently-created XML document is actually a no-brainer process that can be tackled with minor hassles, even if you’re just getting started using the DOM XML extension. So, assuming that you grasped the logic that stands behind this procedure, I’m going to show you another concrete example where different nodes are added to a new XML document, but in this case using a simple PHP array.

Having outlined how this brand new example will work, pay attention to its corresponding source code, which is listed below:

// 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>

<element1>Element 1</element1>

<element2>Element 2</element2>

<element3>Element 3</element3>

<element4>Element 4</element4>

<element5>Element 5</element5>

<element6>Element 6</element6>

<element7>Element 7</element7>

<element8>Element 8</element8>

<element9>Element 9</element9>

<element10>Element 10</element10>

</rootnode>

*/

See how simple it is to build a multi-node XML document by utilizing a basic PHP array to construct the nodes in question? I bet you do! In this case, I used the pair of “createElement()/appendChild()” methods to accomplish this basic task, so since you’ve already seen how they function, you shouldn’t have major problems seeing how the previous example works, right?

However, a brief note is in order here: while the logic implemented by the aforementioned example is actually very simple to grasp, it does demonstrate how easy it is to create complete XML documents from an external source, like a PHP array. Obviously, instead of using array elements, you could use a MySQL database table to build an XML-based representation of the stored data utilizing a script similar to the one shown previously.

This is only one basic example of what you can do with the DOM XML extension, but you’ll find many others as you climb through the corresponding learning curve. In the meantime, feel free to use all the code samples that were developed in this tutorial to acquire a more solid background when using this powerful PHP library.

Final thoughts

In this initial article of the series, I provided you with a quick overview of some basic tasks that you can perform with the DOM XML extension that comes bundled with PHP. From creating XML documents from scratch to adding a few simple nodes, all these things are fairly easy to grasp.

In the next part of the series, I’m going to show you how to use many other features offered by this useful PHP extension, such as adding attributes to existing nodes of an XML document, creating CDATA sections, and much more.