count() function to get number of children of a node
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.
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