#native_company# #native_desc#

Dynamic XML Conversion Using the SAX Parser

By PHP Builder Staff
on April 28, 2003

This article describes an alternative way of converting XML to HTML using the SAX parser.
For each tag you want to convert, you write a conversion function. This function is called
with two arguments: contents and attributes. The return value of the function will replace
the tag and its contents in the finished document.


We all know it: XML is great. (If you don’t, look at some of the great articles at this site.)
But why is it so complicated to use? You have to learn about DTDs, XSLTs, DOM, XPATH, XPOINTER…
this is a lot of work, and most of these techniques are not really neccessary to build a website.
In this article you will learn how to build a simple converter for your XML.
The idea is this: You have a web page in clean XHTML. The biggest part of the html will be
tables, menu images and other design stuff. So why not replace the 30 kilobyte code for the
menu with a nice little “<menu />”?
When the document is opened from a webserver, a small php script replaces the <menu />-tag with
the correct table HTML. So you have a much cleaner document, and the end result is the same. You
can compose your whole page using these meta-tags, and even dynamic tags like <uppercase> or
<showdate /> are easy to program.
These are the steps we will take:
Think up a set of tags that can be used to build an example website.
  • Write functions that convert these tags into HTML.
  • Write a script that takes input from the SAX XML parser and calls the conversion functions with the required arguments
  • Send the output of these functions to the browser
We will use the SAX parser to build the converter. To learn more about SAX and EXPAT
(which is the name of the SAX implementation that PHP uses), please read Justin Grant’s article
PHP and XML: using
expat functions