Created
October 11, 2020 18:05
-
-
Save njh/b5ae7a4399b7c89765c81bc4dbb9df2e to your computer and use it in GitHub Desktop.
A PHP script to compare \EasyRdf\XMLParser with 'XML Parser' (expat)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once realpath(__DIR__)."/vendor/autoload.php"; | |
$xml = <<<'EOD' | |
<root> | |
<one a="1" b="2">one</one> | |
<two a="1" b="2">two</two> | |
<three /> | |
</root> | |
EOD; | |
echo ">>> \EasyRdf\XMLParser\n"; | |
$parser = new \EasyRdf\XMLParser(); | |
$parser->startElementCallback = function($parser) { | |
echo str_repeat(' ', $parser->depth()); | |
echo "start: ".$parser->name."\n"; | |
}; | |
$parser->endElementCallback = function($parser) { | |
echo str_repeat(' ', $parser->depth()); | |
echo "end: ".$parser->name."\n"; | |
}; | |
$parser->textCallback = function($parser) { | |
echo str_repeat(' ', $parser->depth() + 1); | |
echo "text: ".$parser->value."\n"; | |
}; | |
$parser->parse($xml); | |
$parser->close(); | |
echo "<<< \EasyRdf\XMLParser\n"; | |
echo "\n\n"; | |
$depth = 0; | |
function startElementHandler($parser, $name, $attrs) | |
{ | |
global $depth; | |
$depth++; | |
echo str_repeat(' ', $depth); | |
echo "start: $name\n"; | |
} | |
function endElementHandler($parser, $name) | |
{ | |
global $depth; | |
echo str_repeat(' ', $depth); | |
echo "end: $name\n"; | |
$depth--; | |
} | |
function cdataHandler($parser, $data) | |
{ | |
global $depth; | |
if (trim($data) == '') | |
return; | |
echo str_repeat(' ', $depth + 1); | |
echo "text: $data\n"; | |
} | |
echo ">>> xml_parser_create_ns()\n"; | |
$parser = xml_parser_create_ns('UTF-8', ''); | |
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0); | |
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); | |
xml_set_element_handler($parser, 'startElementHandler', 'endElementHandler'); | |
xml_set_character_data_handler($parser, 'cdataHandler'); | |
if (!xml_parse($parser, $xml)) { | |
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); | |
echo "<<< xml_parser_create_ns()\n"; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment