By separating content from presentation, XML offers Web developers a powerful alternative to traditional HTML technology...and when you combine that with PHP, you have a truly compelling new set of tools. In this article, find out how PHP's SAX parser can be used to parse XML data and generate HTML Web pages.
Before we get into the nitty-gritty of XML parsing with PHP, I'd like to take some time to explain how all the pieces fit together.
In case you don't already know, XML is a markup language created to help document authors describe the data contained within a document. This description is accomplished by means of tags, very similar in appearance to regular HTML markup. However, where HTML depends on pre-defined tags, XML allows document authors to create their own tags, immediately making it more powerful and flexible. There are some basic rules to be followed when creating an XML file, and a file can only be processed if these rules are followed to the letter.
Once a file has been created, it needs to be converted, or "transformed", from pure data into something a little more readable. XSL, the Extensible Style Language, is typically used for such transformations; it's a powerful language that allows you to generate different output from the same XML data source. For example, you could use different XSL transformations to create an HTML Web page, a WML deck, and an ASCII text file...all from the same source XML.
There's only one problem here: most browsers don't come with an XML parser or an XSL processor. The latest versions of Internet Explorer and Netscape Gecko do support XML, but older versions don't. And this brings up an obvious problem: how do you use an XML data source to generate HTML for these older browsers
The solution is to insert an additional layer between the client and the server, which takes care of parsing the XML and returning the rendered output to the browser. And that's where PHP comes in - PHP4 supports XML parsing, through its DOM and XML extensions, and even includes an XSL processor, through its Sablotron extension.
Through this article, I'll limit my discussion to PHP's XML parsing functions; I will not be covering XSL transformations or the PHP-Sablotron extension. As you will see, there are two methods to parse XML data with PHP, and each one has advantages and disadvantages; I'll explain both approaches, together with simple examples to demonstrate how to use them in your own applications.