Example 1 — Print Text Between Tags
Register a handler and print every piece of text found in a small note document.
<?php
$xml = '<note><to>Ann</to><from>Bob</from></note>';
$texts = [];
$parser = xml_parser_create();
xml_set_character_data_handler(
$parser,
function (XMLParser $p, string $data) use (&$texts) {
$texts[] = $data;
}
);
xml_parse($parser, $xml, true);
foreach ($texts as $text) {
echo $text, PHP_EOL;
} How It Works
- The XML string has two elements that each contain one word of text.
- xml_set_character_data_handler() stores a closure that receives the parser and the text.
- xml_parse() reads the document and calls the closure for Ann and then for Bob.
- The foreach loop prints the collected text, one piece per line.

