Page 330 - Open Soource Technologies 304.indd
P. 330
Web Technologies-I
Notes The start element handler is called when the XML parser encounters the beginning of an element:
my_start_element_handler(parser, element, attributes);
It is passed three parameters: a reference to the XML parser calling the handler, the name of the
element that was opened, and an array containing any attributes the parser encountered for the
element. The attribute array is passed by reference for speed.
Example contains the code for a start element handler. This handler simply prints the element
name in bold and the attributes in gray.
Start element handler.
function start_element($inParser, $inName, &$inAttributes) {
$attributes = array( );
foreach($inAttributes as $key){
$value = $inAttributes[$key]; $attributes[] = “<font color=\”gray\”>$key=\”$value\” </font>”;
}
echo ‘<<b>’ . $inName . ‘</b> ‘ . join(‘ ‘, $attributes) . ‘>’
;
}
The end element handler is called when the parser encounters the end of an element:
my_end_element_handler(parser, element);
It takes two parameters: a reference to the XML parser calling the handler, and the name of the
element that is closing.
Example shows an end element handler that formats the element.
End element handler.
function end_element($inParser, $inName) { echo ‘<<b>/$inName</b>>’; }
Character Data Handler
All of the text between elements (character data, or CDATA in XML terminology) is handled
by the character data handler. The handler you set with the xml_set_character_data_handler( )
function is called after each block of character data:
xml_set_character_data_handler(parser, handler);
The character data handler takes in a reference to the XML parser that triggered the handler
and a string containing the character data itself:
my_character_data_handler(parser, cdata);
Example shows a simple character data handler that simply prints the data.
Character data handler.
function character_data($inParser, $inData) { echo $inData; }
Processing Instructions
Processing instructions are used in XML to embed scripts or other code into a document. PHP
code itself can be seen as a processing instruction and, with the <?php ... ?> tag style, follows the
XML format for demarking the code. The XML parser calls the processing instruction handler
324 LOVELY PROFESSIONAL UNIVERSITY