Set a function to be called when the parser finds an external entity in the XML document in PHP

Description

The following code shows how to set a function to be called when the parser finds an external entity in the XML document.

Example


//w  w  w.j a  v a 2  s .co m

<?php
    $parser=xml_parser_create();

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

    function ext_ent_handler($parser,$ent,$base,$sysID,$pubID){
       echo "$ent<br />";
       echo "$sysID<br />";
       echo "$pubID<BR />";
    }

    xml_set_character_data_handler($parser,"char");
    xml_set_external_entity_ref_handler($parser, "ext_ent_handler");
    $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>/*ww  w  . j av a  2 s .  c om*/
    <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