i

PHP Tutorial

PHP XML Expat

Expat parser is an event-based XML parser and it returns the XML data as a series of events.

For example: Martin will be reported as three series of event by XML Expat.

Start element : to

Start CDATA section, value : Martin

Close element : to

Let us get detailed explanation of Expat parsing and in-built functions for Expat parsing.

$parser=xml_parser_create();  // To Initialize the parser

// Function that is used at the start of an element
function start($parser,$element_name,$element_attrs) {
  switch($element_name) {
    case "NOTE":
    echo "-- Note --
";
    break;
    case "TO":
    echo "To: ";
    break;
    case "FROM":
    echo "From: ";
    break;
    case "HEADING":
    echo "Heading: ";
    break;
    case "BODY":
    echo "Message: ";
  }
}

// Function that is used at the end of an element
function stop($parser,$element_name) {
  echo "
";
}

// Function that is used when finding character data
function char($parser,$data) {
  echo $data;
}

// To Specify element handler
xml_set_element_handler($parser,"start","stop");

// To Specify data handler
xml_set_character_data_handler($parser,"char");

// To open XML file
$fp=fopen("Reminder.xml","r");

// To Read data
while ($data=fread($fp,4096)) {
  xml_parse($parser,$data,feof($fp)) or
  die (sprintf("XML Error: %s at line %d",
  xml_error_string(xml_get_error_code($parser)),
  xml_get_current_line_number($parser)));
}
 
xml_parser_free($parser);
?>

Let us understand the example in detail:

  1. xml_parser_create() function is used to initialize the XML parser.

  2. Different event handlers are managed using functions.

  3. xml_set_element_handler() function is used to specify the functions to be executed while parsing the opening and closing tags.

  4. xml_set_character_data_handler() function is used to specify the functions that will be execute while parsing character data.

  5. xml_parse() function will parse Reminder.xml file.

  6. xml_error_string() function converts the XML error into a text description.

  7. xml_parser_free() function is used to release the memory that is allocated while initialization.