php8.5
Home/ Manual/ simplexml / simplexmlelement/ SimpleXMLElement::hasChildren

SimpleXMLElement::hasChildren

PHP function Edit on GitHub ✎

(PHP 8)

Checks whether the current element has sub elements

Description

SimpleXMLElement::hasChildren(): bool
Warning

Prior to PHP 8.0, SimpleXMLElement::hasChildren was only declared on the subclass SimpleXMLIterator.

This method checks whether the current SimpleXMLElement element has sub-elements.

Parameters Parameters

Return Values

true if the current element has sub-elements, otherwise false

Examples

Check whether the current element has sub-elements

php
<?php
$xml = <<<XML
<books>
    <book>
        <title>PHP Basics</title>
        <author>Jim Smith</author>
    </book>
    <book>XML basics</book>
</books>
XML;

$xmlElement = new SimpleXMLElement($xml);
for ($xmlElement->rewind(); $xmlElement->valid(); $xmlElement->next()) {
    if ($xmlElement->hasChildren()) {
        var_dump($xmlElement->current());
    }
}
?>

The above example will output:

output
object(SimpleXMLElement)#2 (2) {
  ["title"]=>
  string(10) "PHP Basics"
  ["author"]=>
  string(9) "Jim Smith"
}

Source: reference/simplexml/simplexmlelement/haschildren.xml · from the official PHP manual (php/doc-en)