Chapter 3. PHP and the Document Object Model (DOM)
"A fool sees not the same tree that a wise man sees."William Blake
If you've been paying attention, you now know the basics of parsing XML with PHP. As Chapter 2, "PHP and the Simple API for XML (SAX)" demonstrated, it's pretty simplewhip up some XML data and mix in a few callback functions. It's a simple yet effective recipe, and one that can be used to great effect for the rapid development of XML-based applications.That said, although the event-driven approach to XML parsing is certainly popular, it's not the only option available. PHP also allows you to parse XML using the Document Object Model (DOM), an alternative technique that allows developers to create and manipulate a hierarchical tree representation of XML data for greater flexibility and ease of use.In this chapter, this tree-based approach is explored in greater detail. First it is put under the microscope to see exactly how it works and then PHP's implementation of the DOM is introduced. The various methods exposed by PHP to simplify interaction with the DOM are also examined, together with examples and code listings that demonstrate its capabilities.Both tree- and event-based approaches have significant advantages and disadvantages, and these can impact your choice of technique when implementing specific projects. To that end, this chapter also includes a brief discussion of the pros and cons of each approach in the hope that it will assist you in making the right choice for a particular project.Let's get started!