PHP xml_set_default_handler() function

Definition and Usage

The xml_set_default_handler() function establishes a default data handler for the XML parser.

This function specifies the function to be called whenever the parser finds data in the XML file.

If the handler is successfully established, this function will return true; otherwise, it will return false.

Syntax

xml_set_default_handler(parser,handler)
Parameter Description
parser Required. Specifies the XML parser to be used.
handler Required. Specifies the function used as the event handler.

By handler The function specified by the parameter must have three parameters:

Parameter Description
parser Required. Specifies a variable that contains the XML parser used to call the handler.
data Required. Specifies the variable that contains the data.

Description

handler The parameter can also be an array containing object references and method names.

Example

XML File:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>

PHP Code:

<?php
$parser=xml_parser_create();
function default($parser,$data)
  {
  echo $data;
  }
xml_set_default_handler($parser,"default");
$fp=fopen("test.xml","r");
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);
?>

Output:

George John Reminder Don't forget the meeting!

If you view the source code in the browser, you will see the following HTML:

<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note>