SAX Example Code Page 28
March 8, 2002
In this section we will read an XML file and display it
as an HTML table, using SAX.
This code is based very loosely on the examples posted at http://www.melonfire.com/community/columns/trog/article.php3?id=71
For this example, we need to have two files in the same directory:
In this chapter we will look at:
- travel.xml
- sax_travel.php
<Recordset>
<Travelpackage name="a">
<Country_name>Cuba</Country_name>
<City>Cayo Coco</City>
<Resort>Club Tryp Cayo Coco</Resort>
<Resort_rating>4</Resort_rating>
<Resort_typeofholiday>beach</Resort_typeofholiday>
<Resort_watersports>true</Resort_watersports>
<Resort_meals>true</Resort_meals>
<Resort_drinks>true</Resort_drinks>
<Package>
<Package_dateofdep>5/8/98</Package_dateofdep>
<Package_price>879</Package_price>
</Package>
</Travelpackage>
<Travelpackage name="b">
<Country_name>Cuba</Country_name>
<City>Varadero </City>
<Resort>Sol Club Paleras</Resort>
<Resort_rating>3</Resort_rating>
<Resort_typeofholiday>beach</Resort_typeofholiday>
<Resort_watersports>false</Resort_watersports>
<Resort_meals>true</Resort_meals>
<Resort_drinks>false</Resort_drinks>
<Package>
<Package_dateofdep>5/1/98</Package_dateofdep>
<Package_price>779</Package_price>
</Package>
</Travelpackage>
</Recordset>
There are four main sections of code in the sax_travel.php file:
- The start handler defines the HTML to convert the start tags into
- The end handler defines the HTML for the end tags
- The default handler defines the HTML for the content between the tags
- The call handler is the code that creates and runs the parser
The following code loads an XML file, parses it, and outputs HTML:
<?php
$debug = 0; # Set to 1 to turn on debugging or 0 to turn off debugging.
?>
<html>
<head>
<title>SAX Demonstration</title>
</head>
<body>
<h1>Travel Packages</h1>
<table border="0" cellpadding="0">
<?php
# define the location of the XML document
$file = "./travel.xml";
# use the 'current' vars to keep track of which tag/attribute
# the parser is currently processing
$currentTag = "";
$currentAttribs = "";
The SAX Model
Professional PHP4 Programming
SAX Example Code Page 29
|