Set the character data handler for the XML parser in PHP

Description

The following code shows how to set the character data handler for the XML parser.

Example


/* w  w w.j a  v  a 2s .  c  om*/
<?php
    $parser=xml_parser_create();

    function char($parser,$data){
        echo $data;
    }

    xml_set_character_data_handler($parser,"char");
    $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);
?>

The following code is for test.xml.


    <?xml version="1.0" encoding="UTF-8"?>
    <note>//from   w  w w.java2 s .  c  o m
    <to>Work</to>
    <from>Home</from>
    <heading>Reminder</heading>
    <body>This is a message.</body>
    </note>

The code above generates the following result.





















Home »
  PHP Tutorial »
    XML »




DOM
SimpleXML
SimpleXMLElement
XML Parser