PHP | SimpleXMLElement count() Function

Pre-requisite: Read XML Basics

The SimpleXMLElement::count() function is an inbuilt function in PHP which counts number of child element in a SimpleXML object.

Syntax:



int SimpleXMLElement::count()

Parameter: This function does not accept any parameters.

Return Value: This function returns number of children of an element.

Note: This function is available for PHP 5.3.0 and newer version.

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Loading XML document to $user
$user = <<<XML
<user>
<username> user123 </username>
<name> firstname lastname </name>
<phone> +91-9876543210 </phone>
<detail> I am John Doe. Live in Kolkata, India. </detail>
</user>
XML;
  
// Creating new SimpleXMLElement 
// object from $user
$xml = new SimpleXMLElement($user);
  
// Counting and printing number of
// child of the XML document
echo $xml->count();
  
?>

chevron_right


Output:

4

Example 2: Counting children of child element of the XML document.

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
  
// Loading XML document to $user
$user = <<<XML
<users>
    <user name="user1">
        <username> user123 </username>
        <name> firstname lastname </name>
        <phone> +91-9876543210 </phone>
        <detail> I am John Doe. Live in Kolkata, India. </detail>
        <ins>
            <ins_name>geeks for geeks</ins_name>
            <ins_type>educational</ins_type>
            <ins_url>geeksforgeeks.org</ins_url>
        </ins>
    </user>
    <user name="user2">
        <username> user123 </username>
        <name> firstname lastname </name>
        <phone> +91-9876543210 </phone>
        <detail> I am John Doe. Live in Kolkata, India. </detail>
        <ins>
            <ins_name>geeks for geeks</ins_name>
            <ins_type>educational</ins_type>
            <ins_url>geeksforgeeks.org</ins_url>
        </ins>
    </user>    
</users>
XML;
  
// Creating new SimpleXMLElement
// object from $user
$xml = new SimpleXMLElement($user);
  
echo $xml->count();
  
foreach($xml as $child){
    echo "<br>".$child['name'] . " has " 
        . $child->count()." child.";
}
  
?>

chevron_right


Output:

2
user1 has 5 child.
user2 has 5 child.

Reference: https://www.php.net/manual/en/simplexmlelement.count.php



My Personal Notes arrow_drop_up

I am a programmer by hobby

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.