#native_company# #native_desc#
#native_cta#

Converting XML into a PHP data structure Page 5

By PHP Builder Staff
on December 25, 2002

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:

<?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.
By using the function, xml_set_element_handler, we are
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’:

<?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, xml_set_character_data_handler to define
the callback function as ‘characterData’:

<?php

xml_set_character_data_handler
($this->parser"characterData");

?>



1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|