Example 1 — Turn XML into Arrays
Parse a tiny XML string and print the tags, then look at the index array.
<?php
$xml = '<root><item id="1">Tea</item></root>';
$parser = xml_parser_create();
$result = xml_parse_into_struct($parser, $xml, $values, $index);
echo "Result: ", $result, PHP_EOL;
foreach ($values as $position => $node) {
echo $position, ": ", $node['tag'], " (", $node['type'], ", level ", $node['level'], ")", PHP_EOL;
}
print_r($index); How It Works
- xml_parser_create() makes the parser. No handlers are needed here.
- xml_parse_into_struct() fills $values and $index through references.
- ROOT appears twice, as an open tag and as a close tag, while ITEM is complete because it has only text.
- The index array lists the positions of each tag name in $values.

