SAX Example Code Page 30
March 8, 2002
The next function endElement() defines the HTML to display when
the closing tag is encountered:
function endElement($parser, $name)
{
global $currentTag;
# output closing HTML tags
switch ($name) {
case "Travelpackage":
echo("<tr><td colspan=\"2\"><hr></td></tr>\n");
break;
default:
echo("</td></tr>\n");
break;
}
# clear current tag variable
$currentTag = "";
$currentAttribs = "";
}
Once we decide how each element should be displayed, it becomes
easy to decide what HTML should be put in the different case
statements. In this example we're using the closing
</Travelpackage> tag, as the 'seperator tag' and
displaying a horizontal line to the browser. If there isn't a
need to associate HTML with a tag, leave the case empty.
The function characterData() is used to process the data between
the start and end tags. In the travel.xml document, most
elements contain data. For example, <City>Cayo
Coco</City>, where Cayo Coco is the data. Now we add HTML
to the data $data:
# process data between tags
function characterData($parser, $data)
{
global $currentTag;
# add HTML tags to the values
switch ($currentTag) {
case "Country_name":
echo("<a href=\"#\">$data</a>\n");
break;
default:
echo($data);
break;
}
}
As the parser moves through the XML document it comes across
elements. For example, the parser looks at the element
<Travelpackage name="a"> and matches the element
name with the appropriate case in the switch block. In this
instance, the data should be displayed as a row in the table
with a single cell containing the name and the value of each
attribute within the <Travelpackage> tag. So,
<tr><td>$key: $value</td></tr> is
displayed.
The case statements for <Recordset> and <Package> are empty.
Therefore, nothing will be displayed when the parser sees these
tags. The default case displays <tr><td>$name</td><td> where
$name is the name of the current element, like <City> or
<Resort>. We could create a separate case for every element in
the XML document, or use one common tag for all elements.
Now let us define what the XML will look like when it is parsed
and displayed by the browser. It could display a list, in which
case the default case would look something like:
default:
echo("<li>$name</li>\n");
break;
The next function endElement() defines the HTML to display when the closing tag is encountered:
function endElement($parser, $name)
{
global $currentTag;
# output closing HTML tags
switch ($name) {
case "Travelpackage":
echo("<tr><td colspan=\"2\"><hr></td></tr>\n");
break;
default:
echo("</td></tr>\n");
break;
}
# clear current tag variable
$currentTag = "";
$currentAttribs = "";
}
SAX Example Code Page 29
Professional PHP4 Programming
SAX Example Code Page 31
|