In PHP, SimpleXMLElement::getChildren() returns the child elements of the element that the iterator currently points to.
It belongs to the RecursiveIterator interface that SimpleXMLElement implements in PHP 8. Together with hasChildren(), it lets you walk a tree of nested elements. To read children in normal code, use foreach or the children() method instead.
Syntax
Call SimpleXMLElement::getChildren() with the values you need. Start with this line.
PHP
$children = $xml->getChildren();
Call
What it does
$xml->getChildren()
Returns the element at the current iterator position, ready to be looped over to reach its own children.
$xml->hasChildren()
Checks first whether the current element has child elements.
$xml->children()
The normal way to get the child elements of an element.
getChildren() works on the position of the iterator, so call rewind() and valid() first. Always check hasChildren() before calling getChildren(). If you only need the children of a known element, $xml->children() or foreach is simpler.
walk() loops over the children of the element it receives, using the iterator methods.
For each child it prints the element name, indented by two spaces for every level of depth.
When hasChildren() is true, getChildren() gives the element to walk into, and the depth goes up by one.
The first book shows title and author, and the second book shows title, so the output lists the tree in order.
Frequently Asked Questions
It returns the element at the current iterator position so you can loop over its own child elements. It is part of the RecursiveIterator interface.
children() returns the child elements of the element you call it on. getChildren() works from the iterator position and returns the current child. For normal code, children() is easier.
Call it before getChildren(). It tells you whether the current element has child elements, so you only go deeper when there is something to read.
No. You can read nested values directly, such as $xml->book->title, or loop with foreach. getChildren() is mainly useful when you write a recursive function.
The iterator has no position until rewind() runs. After rewind(), check valid() so you know that the iterator points to a real child.