<?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
$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
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.