Example 1 — Find Where Each Tag Starts
Set an element handler and print the byte index each time a start tag is found.
<?php
$xml = '<root><item id="1">Tea</item></root>';
$parser = xml_parser_create();
xml_set_element_handler(
$parser,
function ($parser, $name) {
echo $name, " starts at byte ", xml_get_current_byte_index($parser), PHP_EOL;
},
function ($parser, $name) {
}
);
xml_parse($parser, $xml, true); How It Works
- xml_parser_create() makes the parser, and xml_set_element_handler() registers the start and end handlers.
- xml_parse() reads the XML and calls the start handler for ROOT and ITEM.
- Inside the handler, xml_get_current_byte_index() returns where that tag begins.
- Tag names are upper case because the parser folds case by default.

