downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

SimpleXMLElement::getDocNamespaces> <SimpleXMLElement::__construct
[edit] Last updated: Fri, 25 May 2012

view this page in

SimpleXMLElement::count

(PHP 5 >= 5.3.0)

SimpleXMLElement::count子要素を数える

説明

public int SimpleXMLElement::count ( void )

このメソッドは、子要素を数えます。

返り値

子要素の数を返します。

例1 子要素の数の取得

<?php
$xml 
= <<<EOF
<people>
 <person name="Person 1">
  <child/>
  <child/>
  <child/>
 </person>
 <person name="Person 2">
  <child/>
  <child/>
  <child/>
  <child/>
  <child/>
 </person>
</people>
EOF;

$elem = new SimpleXMLElement($xml);

foreach (
$elem as $person) {
    
printf("%s has got %d children.\n"$person['name'], $person->count());
}
?>

上の例の出力は以下となります。

Person 1 has got 3 children.
Person 2 has got 5 children.

参考



add a note add a note User Contributed Notes SimpleXMLElement::count
daniel dot erni at focusedpublishing dot com 22-Mar-2011 05:37
Alternative code for PHP < 5.3:
<?php
$count
= $node->count(); // PHP > 5.3
$count = count($node->children()); // PHP < 5.3
?>
Jimmy New Tron 16-Jun-2010 05:17
I used the DOMNodeList $length property to simulate this function since my host had not yet implemented PHP 5.3.  The following code makes it portable and allows you to prepare for an upgrade path.

<?php
$url
= "http://www.example.com/foo.xml";
$xml = simplexml_load_file($url);
// For debugging
// echo "<p>".phpversion()."</p>";
if(phpversion() >= '5.3.0'){
   
$bar_count = $xml->foo->bar->count();
    }
else    {
   
$doc = new DOMDocument();
   
$str = $xml->asXML();
   
$doc->loadXML($str);
   
$bar_count = $doc->getElementsByTagName("bar")->length;
    }
echo
"There are ".$bar_count." \"bar\" nodes in this document.<br />";
?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites