Background
[wp_ad_camp_1]
With XML Parser, you use callback functions to deal with specific events such as when the start or end of an XML element is encountered. These functions are registered using API functions made available for the XML Parser extension and are triggered or executed when a specific event is encountered. Also, you can only read XML with this extension.
Software Requirements
- Windows 7 Professional SP1
- PHP 5.5.9 / Zend Engine v2.5.0
- NetBeans IDE 8.0.1
- ApacheFriends XAMPP Version 1.8.3
- Apache/2.4.7 (Win32) / Open SSL/1.0.1e
XML Parser
The basic steps in reading an XML document using XML Parser are as follow:
- Create a new parser resource by calling the xml_parser_create() function12// Creates a parser resource$parser = xml_parser_create();
- Create two callback functions to handle the start and end of an XML document, and register them with the parser using the xml_set_element_handler() function.123456789101112function startElement($parser, $element, $attributes) {echo "Start of Element: $element\n";foreach($attributes as $key=>$value) {echo " Attribute: $key | value: $value \n";}}function endElement($parser, $element) {echo "End of Element: $element\n";}xml_set_element_handler($parser, "startElement", "endElement");
- Create another callback function to handle any character data within an element, and register it with the parser using xml_set_character_data_handler() function.
[wp_ad_camp_4]
1234function characterDataHandler($parser, $data ) {echo "Data: $data \n";}xml_set_character_data_handler( $parser, "characterDataHandler"); - Parse the XML document using xml_parse() function and passing the parser resource and the XML string to parse.1xml_parse($parser, "<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>");
- Destroy the parser1xml_parser_free($parser);
When executed as PHP file, the codes above output the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Start of Element: NOTE Start of Element: TO Data: Tove End of Element: TO Start of Element: FROM Data: Jani End of Element: FROM Start of Element: HEADING Data: Reminder End of Element: HEADING Start of Element: BODY Data: Don't forget me this weekend! End of Element: BODY End of Element: NOTE |
Dealing with Parse Errors
The xml_parse() function returns either true or false. If it returns false, there was a problem encountered while parsing the XML. The details of the problem can be determine using some other XML Parser functions:
- xml_get_error_code($parser)
This returns an error code of the last error encountered - xml_error_string($code)
This returns the string describing the error code returned by xml_get_error_code() - xml_get_current_line_number($parser) and xml_get_current_column_number($parser)
These returns the location of the cause of the error in the XML
[wp_ad_camp_5]