当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


PHP SimpleXMLElement count()用法及代码示例


前提条件: 阅读XML基础

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

用法:


int SimpleXMLElement::count()

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

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

注意:此函数可用于PHP 5.3.0和更高版本。

示例1:

<?php 
  
// Loading XML document to $user 
$user = <<<XML 
<user> 
<username> user123 </username> 
<name> firstname lastname </name> 
<phone> +91-9876543210 </phone> 
<detail> I am John Doe. Live in Kolkata, India. </detail> 
</user> 
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文档的child元素的child。

<?php 
  
// Loading XML document to $user 
$user = <<<XML 
<users> 
    <user name="user1"> 
        <username> user123 </username> 
        <name> firstname lastname </name> 
        <phone> +91-9876543210 </phone> 
        <detail> I am John Doe. Live in Kolkata, India. </detail> 
        <ins> 
            <ins_name>geeks for geeks</ins_name> 
            <ins_type>educational</ins_type> 
            <ins_url>geeksforgeeks.org</ins_url> 
        </ins> 
    </user> 
    <user name="user2"> 
        <username> user123 </username> 
        <name> firstname lastname </name> 
        <phone> +91-9876543210 </phone> 
        <detail> I am John Doe. Live in Kolkata, India. </detail> 
        <ins> 
            <ins_name>geeks for geeks</ins_name> 
            <ins_type>educational</ins_type> 
            <ins_url>geeksforgeeks.org</ins_url> 
        </ins> 
    </user>     
</users> 
XML; 
  
// Creating new SimpleXMLElement 
// object from $user 
$xml = new SimpleXMLElement($user); 
  
echo $xml->count(); 
  
foreach($xml as $child){ 
    echo "<br>".$child['name'] . " has " 
        . $child->count()." child."; 
} 
  
?>

输出:

2
user1 has 5 child.
user2 has 5 child.

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



相关用法


注:本文由纯净天空筛选整理自gekcho大神的英文原创作品 PHP | SimpleXMLElement count() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。