SAX Example Code Page 29
March 8, 2002
In the startElement function we define what HTML is associated
with which element. The function startElement is called by the
xml_set_element_handler function in the code. The startElement
function must have three parameters:
- $parser
This parameter refers back to the instance of the xml parser
that we create
- $name
This parameter refers to the name of the element in the
XML document
- $attribs
This parameter refers to any Attributes in the Element.
In our sample XML we have <City>Cayo Coco</City>
where <City> is the start element.
By default, the value of the element is case-folded, that is, it
is converted to uppercase. We change the case folding a little
further on in the code. If case folding is on, then the case
statement will have the name in uppercase:
case "RECORDSET":
If case folding is turned on, the parser will not match the name
of the element, i.e. Recordset does not match RECORDSET. This
violates the XML 1.0 specification:
function startElement($parser, $name, $attribs)
{
global $currentTag, $currentAttribs;
$currentTag = $name;
$currentAttribs = $attribs;
# define the HTML to use for the start tag.
switch ($name) {
case "Recordset":
break;
case "Travelpackage":
while (list ($key, $value) = each ($attribs)) {
echo("<tr><td>$key: $value</td></tr>\n");
}
break;
case "package":
break;
default:
echo("<tr><td>$name</td><td>\n");
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;
SAX Example Code Page 28
Professional PHP4 Programming
SAX Example Code Page 30
|