【问题标题】:how to count the raw element fo the xml file? [duplicate]如何计算 xml 文件的原始元素? [复制]
【发布时间】:2012-09-04 10:43:15
【问题描述】:

可能重复:
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); 时,结果是“0”而不是 10(字符串中的行);

我应该怎么做才能在变量 $data_count 中包含原始数字? 非常感谢。

【问题讨论】:

  • instead 10(rows in the string);是什么意思
  • 以及相关部分中的更多内容。提问前请使用搜索功能。当我们要求您在stackoverflow.com/questions/ask-advice 中做作业时,我们是认真的
  • "结果 [原文如此] 是 "0" 而不是 10(字符串中的行);" — 我很难看到你有 10 个,你能解释一下什么是“行”?

标签: php xml


【解决方案1】:

你应该试试

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

Demo

【讨论】:

  • 致命错误:调用 /homepages/26/d94605010/htdocs/lz/writecodeonline.com/php/index.php(201) 中未定义的方法 SimpleXMLElement::count() : eval()' d 代码在第 16 行
  • 您使用的是什么版本的 PHP .. 在这里查看现场演示:codepad.viper-7.com/rE72A4 它工作正常
【解决方案2】:

试试这个

$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

【讨论】:

    【解决方案3】:

    你也可以这样试试:

    <?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 ) );
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 2014-04-08
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      相关资源
      最近更新 更多