PHP Function Reference

PHP xml_set_processing_instruction_handler() Function



The PHP xml_set_processing_instruction_handler() function sets the processing instruction (PI) handler function for the given XML parser.

A processing instruction is enclosed in <? and ?> and contains the target data. For example - a PI associates a style sheet with an XML document is given below:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="default.xsl" type="text/xml"?>
<userlist>
  <user>
    <username>John123</username>
    <name>John Smith</name>
    <phone>+1-8054098000</phone>
    <address>Brooklyn, New York, USA</address>
  </user>
</userlist>  

Syntax

xml_set_processing_instruction_handler(parser, handler)

Parameters

parser Required. Specify a reference to the XML parser to set up processing instruction (PI) handler function.
handler Required. Specify a string containing the name of a function to be used as an event handler. The function must accept three parameters:
handler(parser, target, data)
  • parser: The first parameter, parser, is a reference to the XML parser calling the handler.
  • target: The second parameter, target, contains the PI target.
  • data: The third parameter, data, contains the PI data.
If a handler function is set to an empty string, or false, the handler in question is disabled. Note: Instead of a function name, an array containing an object reference and a method name can also be supplied.

Return Value

Returns true on success or false on failure.

Example: xml_set_processing_instruction_handler() example

Lets assume that we have a file called test.xml. In the example below, an XML parser is created using xml_parser_create() function. Then the XML file is opened to parse its data using character handler function char_print. Then the pi_handler function is set as processing instruction handler function for the given XML parser. After parsing the document, the parser is freed using xml_parser_free() function.

<?php
//create an XML parser
$parser=xml_parser_create();

//character handler function for XML parser
function char_print($parser, $data) {
  echo $data;
}

//processing instruction handler function for XML parser
function pi_handler($parser, $target, $data) {
  echo "$target $data \n";
}

//set the character handler function for XML parser
xml_set_character_data_handler($parser,"char_print");

//set the processing instruction handler function for XML parser
xml_set_processing_instruction_handler($parser,"pi_handler");

//opening xml file
$fp = fopen("test.xml", "r");

while($data = fread($fp,4096)) {
  //parsing XML data
  xml_parse($parser,$data,feof($fp)) or

    //displaying error when parse error occurs
    die (sprintf("XML Error: %s at line %d",

    //error string
    xml_error_string(xml_get_error_code($parser)),

    //current line
    xml_get_current_line_number($parser)));
}

//free XML parser
xml_parser_free($parser);

fclose($fp);
?>

❮ PHP XML Parser Reference