Software Development

How to read XML Document using the XML Parser extension in PHP

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:

  1. Create a new parser resource by calling the xml_parser_create() function
  2. 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.
  3. 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]
  4. Parse the XML document using xml_parse() function and passing the parser resource and the XML string to parse.
  5. Destroy the parser

When executed as PHP file, the codes above output the following:

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:

  1. xml_get_error_code($parser)
    This returns an error code of the last error encountered
  2. xml_error_string($code)
    This returns the string describing the error code returned by xml_get_error_code()
  3. 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]

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like