PHP SimpleXML函数

PHP SimpleXMLElement::count() 方法计算元素的子元素数量。

语法

public SimpleXMLElement::count()

参数

不需要参数。

返回值

返回元素数量

示例:

下面的示例显示了 SimpleXMLElement::count() 方法的用法。

<?php
$xml = <<<XML
<userlist> 
  <user id="John123">
    <name>John Smith</name>
    <city>New York</city>
    <phone>+1-8054098000</phone>
    <address>Brooklyn, New York, USA</address>
  </user>
  
  <user id="Marry2015">
    <name>Marry G.</name>
    <phone>+33-147996101</phone>
  </user> 
</userlist> 
XML;

$elem = new SimpleXMLElement($xml);
foreach ($elem as $user) {
  printf("%s has %d children. \n", 
         $user['id'], $user->count());
}
?>

上述代码的输出将是:

John123 has 4 children.
Marry2015 has 2 children.