Example 1 — Catch a Comment
Set element, character data, and default handlers, then see that the comment is the only thing the default handler receives.
<?php
$xml = '<list><!--first--><item>A</item></list>';
$other = [];
$text = '';
$parser = xml_parser_create();
xml_set_element_handler(
$parser,
function (XMLParser $p, string $name) {
},
function (XMLParser $p, string $name) {
}
);
xml_set_character_data_handler(
$parser,
function (XMLParser $p, string $data) use (&$text) {
$text .= $data;
}
);
xml_set_default_handler(
$parser,
function (XMLParser $p, string $data) use (&$other) {
$other[] = $data;
}
);
xml_parse($parser, $xml, true);
echo 'Default: ', implode(' | ', $other), PHP_EOL;
echo 'Text: ', $text, PHP_EOL; How It Works
- The element handlers take care of every start and end tag, so tags never reach the default handler.
- The character data handler collects the text A.
- The comment has no handler of its own, so the parser passes it to the default handler.
- The default handler receives the raw comment text, including the comment markers.

