Example 1 — Print the Name of Each Child
Loop with the iterator methods and print the name and text of each child element.
<?php
$xml = simplexml_load_string(
'<menu><item>Tea</item><item>Coffee</item><drink>Juice</drink></menu>'
);
for ($xml->rewind(); $xml->valid(); $xml->next()) {
echo $xml->key(), ' => ', $xml->current(), PHP_EOL;
} How It Works
- The menu element has three children: two item elements and one drink element.
- rewind() starts at the first child, and valid() keeps the loop going while a child exists.
- key() returns the element name and current() returns the element, so echo prints both.
- The name item appears twice, which shows that keys are names and can repeat.

