PHP Function Reference

PHP SimpleXMLIterator - hasChildren() Method



The PHP SimpleXMLIterator::hasChildren() method checks whether the current SimpleXMLIterator element has sub-elements.

Syntax

public SimpleXMLIterator::hasChildren()

Parameters

No parameter is required.

Return Value

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

Example: check whether the current element has sub-elements

The example below shows the usage of SimpleXMLIterator::hasChildren() method.

<?php
$xml = <<<XML
<userlist> 
  <user id="John123">
    <name>John Smith</name>
    <city>New York</city>
  </user>
  
  <user id="Marry2015"></user> 
</userlist> 
XML;

$xmlIterator  = new SimpleXMLElement($xml);

for($xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next()) {
  if($xmlIterator->hasChildren()) {
    var_dump($xmlIterator->current());
  }
}
?>

The output of the above code will be:

object(SimpleXMLElement)#2 (3) {
  ["@attributes"]=>
  array(1) {
    ["id"]=>
    string(7) "John123"
  }
  ["name"]=>
  string(10) "John Smith"
  ["city"]=>
  string(8) "New York"
}

❮ PHP SimpleXML Reference