📜  PHP | SimpleXMLElement count()函数

📅  最后修改于: 2022-05-13 01:56:22.264000             🧑  作者: Mango

PHP | SimpleXMLElement count()函数

先决条件:阅读 XML 基础知识

SimpleXMLElement::count()函数是PHP中的一个内置函数,用于计算 SimpleXML 对象中子元素的数量。

句法:

int SimpleXMLElement::count()

参数:此函数不接受任何参数。

返回值:此函数返回元素的子元素数。

注意:此函数适用于PHP 5.3.0 及更新版本。

示例 1:


 user123 
 firstname lastname 
 +91-9876543210 
 I am John Doe. Live in Kolkata, India. 

XML;
  
// Creating new SimpleXMLElement 
// object from $user
$xml = new SimpleXMLElement($user);
  
// Counting and printing number of
// child of the XML document
echo $xml->count();
  
?>

输出:

4

示例 2:计算 XML 文档的子元素的子元素。


    
         user123 
         firstname lastname 
         +91-9876543210 
         I am John Doe. Live in Kolkata, India. 
        
            geeks for geeks
            educational
            geeksforgeeks.org
        
    
    
         user123 
         firstname lastname 
         +91-9876543210 
         I am John Doe. Live in Kolkata, India. 
        
            geeks for geeks
            educational
            geeksforgeeks.org
        
        

XML;
  
// Creating new SimpleXMLElement
// object from $user
$xml = new SimpleXMLElement($user);
  
echo $xml->count();
  
foreach($xml as $child){
    echo "
".$child['name'] . " has "          . $child->count()." child."; }    ?>

输出:

2
user1 has 5 child.
user2 has 5 child.

参考: https://www. PHP.net/manual/en/simplexmlelement.count。 PHP