Iterate SimpleXML Safely Before Calling key()

Do not read key() from a newly created SimpleXML iterator before positioning it. Prefer foreach, which initializes the iterator automatically. When manual control is necessary, call rewind() and verify valid() before reading key() or current().

Last updated: October 27, 2026.

<?php
$xml = new SimpleXMLIterator(
    '<items><item id="A"/><item id="B"/></items>'
);

// Preferred: foreach manages the iterator state.
foreach ($xml as $key => $item) {
    echo $key . ': ' . (string) $item['id'] . PHP_EOL;
}

// Manual traversal when you need explicit control.
$xml->rewind();
while ($xml->valid()) {
    $key = $xml->key();
    $item = $xml->current();
    echo $key . ': ' . (string) $item['id'] . PHP_EOL;
    $xml->next();
}

The order matters in the manual loop: position the iterator, test that the position is valid, read the key and value, and then advance. Never use a truthiness test on the key itself because a valid key is not a validity signal.

Let foreach handle ordinary traversal

The PHP iterator documentation explains that foreach calls rewind() when iteration starts. That makes it the clearest choice when every child should be processed in order. It also keeps state-management calls out of application code.

SimpleXMLIterator supports recursive traversal, but its iterator methods are inherited from SimpleXMLElement. The SimpleXMLElement class reference lists rewind(), valid(), key(), current(), and next() as one iterator contract. Use them as a sequence rather than calling key() in isolation.

Use manual traversal only when state matters

A manual loop is appropriate when code must pause, resume, inspect children recursively, or coordinate several iterators. Rewind once before the loop. Check valid() before every read, because an empty XML element has no current child and next() eventually moves beyond the final child.

Keep XML parsing separate from validation. SimpleXML can load well-formed XML while required elements or attributes are still missing, so validate the expected structure before using values in database queries or business rules. For related patterns, see exporting a database schema as XML, writing clear PHP functions, and traversing PHP data safely.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov