Once we’ve built this class to wrap the PHP parser, we can create an instance
of the class and have it parse the XML sample code we described above. Some
sample code to do this would look as follows:
of the class and have it parse the XML sample code we described above. Some
sample code to do this would look as follows:
<?php
$xml2a = new XMLToArray();
$xml2a->parse($xml_text);
?>
Watching The XML Parsing Events: Callback Functions
What do we expect to happen when the above code is executed? Well, each time
the xml_parse function encounters an XML tag in our document, it’ll fire an
event by calling the functions we told it to call. The term for this behavior
is often refered to as a ‘Callback Function’. Basically we want PHP to call
us back at a given function name each time it triggers an event of a certain
type.
the xml_parse function encounters an XML tag in our document, it’ll fire an
event by calling the functions we told it to call. The term for this behavior
is often refered to as a ‘Callback Function’. Basically we want PHP to call
us back at a given function name each time it triggers an event of a certain
type.
By using the function,
letting the PHP parser know that the open tag should invoke a method in
our class named ‘startElement’ and all close tags should invoke a method in
our class named ‘endElement’:
xml_set_element_handler
, we areletting the PHP parser know that the open tag should invoke a method in
our class named ‘startElement’ and all close tags should invoke a method in
our class named ‘endElement’:
<?php
xml_set_element_handler($this->parser, "startElement", "endElement");
?>
Additionally, we want to capture all the character data between tags, so we
use the method,
the callback function as ‘characterData’:
use the method,
xml_set_character_data_handler
to definethe callback function as ‘characterData’:
<?php
xml_set_character_data_handler($this->parser, "characterData");
?>