PHP/XML/XML Handler

Материал из Web эксперт
Перейти к: навигация, поиск

Parsing a Processing Instruction

<?php
     function pi_handler ($p, $target, $data) {
        print ($target);
        print ($data);
     }
     $xml = "<?exec ls -l /var?><rootElement/>";
     $p = xml_parser_create ();
     xml_set_processing_instruction_handler ($p, "pi_handler");
     if (!xml_parse ($p, $xml, true))
          die (sprintf ("Parse error in <code>%s</code> (%s)",
                        htmlspecialchars ($xml),
                        xml_error_string (xml_get_error_code ($p))));
     else
          print ("XML processing complete.\n");
     xml_parser_free ($p);
?>



Using a Default Handler

<?php
     $i = 1;
     function default_handler ($p, $data)
     {
          global $i;
          print ("$i: default: $data\n");
          $i++;
     }
     
     function cdata_handler ($p, $data)
     {
          global $i;
          print ("$i: cdata: $data\n");
          $i++;
     }
     $xml = "<foo>bar</foo><?exec command ?>";
     
     $p = xml_parser_create ();
     xml_set_default_handler ($p, "default_handler");
     xml_set_character_data_handler ($p, "cdata_handler");
     
     if (!xml_parse ($p, $xml, true)){
          die (sprintf ("<br />Parse error in <code>%s</code> (%s)",
                        htmlspecialchars ($xml),
                        xml_error_string (xml_get_error_code ($p))));
     }
     xml_parser_free ($p);
?>



XML Cdata handler

<?php
     function cdata_handler ($parser, $data) { 
        print ($data); 
     }
     
     $xml = "<para>some character data</para>";
     $parser = xml_parser_create ();
     xml_set_character_data_handler ($parser, "cdata_handler");
     
     if (xml_parse ($parser, $xml, true))
          print ("Your XML document is well-formed.");
     else
          print ("Your XML document is not well-formed.");
     
     xml_parser_free ($parser);
?>