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.

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 
Visitors Rating
Your Rating





Post your comments , suggestion , error , requirements etc here .




HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer