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.
The first of these approaches is SAX, the Simple API for XML. A SAX parser works by traversing an XML document and calling specific functions as it encounters different types of tags. For example, I might call a specific function to process a starting tag, another function to process an ending tag, and a third function to process the data between them.
The parser's responsibility is simply to parse the document; the functions it calls are responsible for processing the tags found. Once the tag is processed, the parser moves on to the next element in the document, and the process repeats itself.
PHP comes with the expat parser, which you can also download from http://www.jclark.com/xml/. You may need to recompile your PHP binary with the "--with-xml" parameter to activate XML support (Windows users get a pre-built binary with their distribution.)
I'll begin by putting together a simple XML file:
Lord Of The Rings</title>
<author>J. R. R. Tolkien</author>
Once my data is in XML-compliant format, I need to decide what I'd like the final
output to look like. Let's say I want it to look like this:
As you can see, this is a simple table containing columns for the book title, author, price and rating. (I'm not using all the information in the XML file.) The title of the book is printed in italics, while the numerical rating is converted into something more readable.
Next, I'll write some PHP code to take care of this for me.