前提條件: 閱讀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
相關用法
- PHP SimpleXMLElement addChild()用法及代碼示例
- PHP SimpleXMLElement asXML()用法及代碼示例
- PHP SimpleXMLElement::getName()用法及代碼示例
- PHP SimpleXMLElement::__construct()用法及代碼示例
- PHP SimpleXMLElement saveXML()用法及代碼示例
- PHP SimpleXMLElement addAttribute()用法及代碼示例
- PHP SimpleXMLElement getNamespaces()用法及代碼示例
- PHP SimpleXMLElement registerXPathNamespace()用法及代碼示例
- PHP SimpleXMLElement XPath()用法及代碼示例
- PHP SimpleXMLElement attributes()用法及代碼示例
- PHP SimpleXMLElement getDocNamespaces()用法及代碼示例
- PHP SimpleXMLElement children()用法及代碼示例
- PHP Ds\Map count()用法及代碼示例
- PHP Ds\Set count()用法及代碼示例
- PHP count()用法及代碼示例
注:本文由純淨天空篩選整理自gekcho大神的英文原創作品 PHP | SimpleXMLElement count() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。