count() function to get number of children of a node

Count XML child elements

Use count() on a SimpleXMLElement when you need the number of direct child elements.

<?php
$xml = simplexml_load_string('<book><title>PHP</title><year>2026</year></book>');
echo count($xml->children());
?>

Current example first; the detailed examples below are retained for additional learning and comparison.

We can get number of children present in XML element by using count() function. Here at different levels of node of the XML data we can get the number of children by using count function.

We will be using our sample page for this.

xml-sample1.php

<?php
$str_xml = <<<XML
<?xml version='1.0' standalone='yes'?>
<details>
<name>Abcd</name>
<address>
  	<door_no>234-ac</door_no>
	<street>Great Wall</street>
	<city>Alabama</city>
</address>

</details>
XML;
?>
To make it more useful we will be using getName function to read about the element name along with the number of children present in that element.
<?php
require "xml-sample1.php";
$main1 = new SimpleXMLElement($str_xml);
echo "<b>getName</b> : ".$main1->getName()." Number of children : ".$main1->count()."</b><br>";
?>
The output is
getName : details Number of children : 2
To get the number of children at different nodes we will be using children function. Here is the complete code.
<?php
require "xml-sample1.php";
$main1 = new SimpleXMLElement($str_xml);
echo "<b>getName</b> : ".$main1->getName()." Number of children : ".$main1->count()."</b><br>";

foreach ($main1->children() as $child1) {
echo  '<br><b>getName</b> : '.$child1->getName().' Number of children : ' .$child1->count();

foreach ($child1->children() as $child2) {
echo  '<br><b>getName</b> : '.$child2->getName().' Number of children : ' .$child2->count();
}
}
?>
The output is here.
getName : name Number of children : 0

getName : address Number of children : 3

getName : door_no Number of children : 0

getName : street Number of children : 0

getName : city Number of children : 0
For PHP version less than 5.3 we have to use like this.
$total =count($child2->children()); // for < php 5.3 version

Use the xml file file-xml-demo.php

$xml = simplexml_load_file('file-xml-demo.xml');
     
 echo $xml->student->count(); // Output is 0
 echo "<br>";
 echo $xml->details->count(); // Output 34
 echo "<br>";
 echo $xml->details[3]->count();     // Output 3 

XML XML Children



Subscribe to our YouTube Channel here



plus2net.com











PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer