如何计算xml文件的原始元素?

时间:2012-09-04 10:43:16

标签: php xml

  

可能重复:
  SimpleXML: How to find number of children of top-level element?
  php count xml elements

我有这段代码:

$string = <<<XML
<?xml version='1.0'?> 
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string);
$data_count = count($data->xml);
print_r($data_count);

我在第Demo

上运行此代码

当我执行print_r($data_count);时,resualt为“0”而不是10(字符串中的行);

我该怎么做才能在变量$data_count中包含原始数字? 许多人。

3 个答案:

答案 0 :(得分:1)

你应该试试

$xml = simplexml_load_string($string);
print_r($xml->count()); // 4

Demo

答案 1 :(得分:0)

试试这个

$string = <<<XML
<?xml version='1.0'?> 
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
  I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml = simplexml_load_string($string); 
$data_count = count($xml);//here you need to give the parser object
print_r($data_count);
echo count($xml->title); //No of title tags

答案 2 :(得分:0)

你也可以尝试这样:

<?php

$string = "XML
<?xml version='1.0'?> 
  <document>
    <title>Forty What?</title>
    <from>Joe</from>
    <to>Jane</to>
    <body>
      I know that's the answer -- but what's the question?
    </body>
  </document>
XML";

$array = explode( "\r", $string );

print_r( sizeof( $array ) );

?>