Example 1 — Create, Set Handlers, Parse
This is the standard flow: create a parser, set the handlers, and call xml_parse() with a small XML string.
<?php
$xml = '<root><item id="1">Tea</item></root>';
$parser = xml_parser_create();
xml_set_element_handler(
$parser,
function ($parser, $name, $attrs) {
echo "Start: ", $name, PHP_EOL;
},
function ($parser, $name) {
echo "End: ", $name, PHP_EOL;
}
);
xml_set_character_data_handler(
$parser,
function ($parser, $data) {
echo "Text: ", $data, PHP_EOL;
}
);
$result = xml_parse($parser, $xml, true);
echo "Result: ", $result, PHP_EOL; How It Works
- xml_parser_create() makes the XMLParser object.
- The element handler and character data handler describe what to do for tags and text.
- xml_parse() reads the XML and calls the handlers in document order.
- It returns 1 because the XML is valid. Names are upper case by default.

