Page 621 - Beginning PHP 5.3
P. 621

Chapter 19: Working with XML
                           Creating Event Handlers

                           Now that you have a parser to work with, you need to create functions to handle the start of an XML
                         element, the end of an element, and character data.

                           The function that deals with the start of an element needs to accept three arguments: the parser resource,
                         the element name, and an associative array of any attributes in the element. For example:
                             function startElementHandler( $parser, $element, $attributes )
                             {
                               // (process the start of the element)
                             }

                          The end - element handler is similar, but it doesn ’ t have to deal with attributes:
                             function endElementHandler( $parser, $element )
                             {
                               // (process the end of the element)
                             }

                           Finally, the character data handler needs to accept the parser resource, and a string containing the
                         character data. For example:

                             function characterDataHandler( $parser, $data )
                             {
                               // (process the character data)

                             }
                           Obviously the example handlers don ’ t do any actual processing of the elements or data. You write real
                         handlers in a moment.

                          Once you ’ ve created your three event handlers, you register them with the parser. To register the start
                         and end handlers use   xml_set_element_handler() , passing in the parser resource, followed by the
                          names of the start element handler and end element handler functions as strings. For example:

                             xml_set_element_handler( $parser, “startElementHandler”, “endElementHandler” );
                           To register the character data handler call  xml_set_character_data_handler() , passing in the parser
                         resource followed by the handler function ’ s name as a string:
                             xml_set_character_data_handler( $parser, “characterDataHandler” );
















                                                                                                         583





                                                                                                      9/21/09   9:17:46 AM
          c19.indd   583
          c19.indd   583                                                                              9/21/09   9:17:46 AM
   616   617   618   619   620   621   622   623   624   625   626