PHP Function Reference

PHP SimpleXMLElement - count() Method



The PHP SimpleXMLElement::count() method counts the number of children of an element.

Syntax

public SimpleXMLElement::count()

Parameters

No parameter is required.

Return Value

Returns the number of elements of an element.

Example:

The example below shows the usage of SimpleXMLElement::count() method.

<?php
$xml = <<<XML
<userlist> 
  <user id="John123">
    <name>John Smith</name>
    <city>New York</city>
    <phone>+1-8054098000</phone>
    <address>Brooklyn, New York, USA</address>
  </user>
  
  <user id="Marry2015">
    <name>Marry G.</name>
    <phone>+33-147996101</phone>
  </user> 
</userlist> 
XML;

$elem = new SimpleXMLElement($xml);
foreach ($elem as $user) {
  printf("%s has %d children. \n", 
         $user['id'], $user->count());
}
?>

The output of the above code will be:

John123 has 4 children.
Marry2015 has 2 children.

❮ PHP SimpleXML Reference