Using PHP with XML (part 2) (
Page 1 of 6 )
PHP offers two methods of parsing an XML document. You've already seen how SAX
works; in this article, find out how to use PHP's DOM functions to traverse an
XML tree, and also learn about important differences between the two approaches.In the first part of this article, I said that there were two approaches to parsing
an XML document. SAX is one; the other uses the DOM to build a tree representation
of the XML data structures in the document, and then offers built-in methods to
navigate through this tree. Once a particular node has been reached, built-in
properties can be used to obtain the value of the node, and use it within the
script.
PHP4 comes with support for this "DOM parser" as well, although you may need
to recompile your PHP binary with the "--with-dom" parameter to activate it. Windows
users get a free ride, since a compiled binary is included with their distribution;
however, they will still need to activate the extension in the "php.ini" configuration
file.
Over the next few pages, I'm going to take a look at PHP's DOM functions, illustrating
an alternative method of parsing XML data. I'll also attempt to duplicate the
previous examples, marking up books and recipes with HTML tags, in order to demonstrate
how either technique can be used to achieve the same result. Finally, I'll briefly
discuss the pros and cons of the SAX and DOM approaches, and point you to some
links for your further education.
Let's get started, shall we?