• PHP Video Tutorials

PHP - SimpleXMLElement::count() Function



Definition and Usage

XML is a mark-up language to share the data across the web, XML is for both human read-able and machine read-able. The SimpleXMLElement class represents an XML document in PHP.

The SimpleXMLElement::count() function counts the number of children of an XML element.

Syntax

SimpleXMLElement::count();

Parameters

This function does not accept any parameters.

Return Values

This function returns an integer value representing the number of child elements of an XML Element.

PHP Version

This function was first introduced in PHP Version 5 and works in all the later versions.

Example

Following example demonstrates the usage of the SimpleXMLElement::count() function.

<html>
   <head>
      <body>
         <?php
            $str = "<?xml version='1.0' standalone='yes'?>
            <Tutorial>
               <Name type = 'programming'>JavaFX</Name>
               <Pages>535</Pages>
               <Author>Krishna</Author>
               <Version>11</Version>
            </Tutorial>";
            $xml = new SimpleXMLElement($str);
            print("Number of child elements: ".$xml->count());
         ?>      
      </body>
   </head>   
</html> 

This will produce following result −

Number of child elements: 4

Example

In the following example we are trying to read the contents of an XML file, this programs prints the number of records of the XML file −

data.xml:

<?xml version="1.0" encoding="utf-8"?>
<Tutorials>
   <Tutorial>
      <Name>JavaFX</Name>
      <Pages>535</Pages>
      <Author>Krishna</Author>
      <Version>11</Version>
   </Tutorial>

   <Tutorial>
      <Name>CoffeeScript</Name>
      <Pages>235</Pages>
      <Author>Kasyap</Author>
      <Version>2.5.1</Version>
   </Tutorial>
   
   <Tutorial>
      <Name>OpenCV</Name>
      <Pages>150</Pages>
      <Author>Maruti</Author>
      <Version>3.0</Version>
   </Tutorial>
</Tutorials>

sample.php:

<html>
   <head>      
      <body>         
         <?php
            $doc = new DOMDocument;
            $xml = simplexml_load_file("trail.xml");
            //file to SimpleXMLElement 
            $xml = simplexml_import_dom($xml);
            print("Number of child elements: ".$xml->count());	
         ?>
      </body>
   </head>
</html>

This will produce the following output −

Number of child elements: 3
php_function_reference.htm
Advertisements