【问题标题】:Count how many children are in XML with PHP用 PHP 计算 XML 中有多少孩子
【发布时间】:2015-08-01 10:17:07
【问题描述】:

我对php有一些了解,很抱歉这个问题:

我有这个文件 xml:

 <?xml version="1.0" encoding="ISO-8859-1"?>
  <alert>
   <status> </status>
   <nothing> </nothing>
   <info>
    <area>
    </area>
   </info>
   <info>
    <area>
    </area>
   </info>
   <info>
    <area>
    </area>
   </info>
  </alert>

我必须做一个 for 循环,并在一个“foreach”中为每个 问题是我不确定有什么方法可以知道我必须重复 for 循环多少次。因为在这个文件 xml 中(这是一个例子)我不知道有多少

如果:

$url = "pathfile";
$xml = simplexml_load_file($url);
$numvulcani = count($xml->alert->info); // is good ?

for ($i = 0; $i <= $numvulcani; $i++) {
 foreach ($xml->alert->info[$i] as $entry) {
  $area = $entry->area;
 }
}

是真的吗?

抱歉英语不好

【问题讨论】:

  • 你想达到什么目的?你试过foreach循环吗?
  • 我想知道我的例子中的 count() 是否好:/

标签: php xml simplexml


【解决方案1】:

您需要为此使用 SimpleXMLElement::count 函数 - 它计算元素的子元素。

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

输出如下:

第 1 个人有 3 个孩子。 第 2 个人有 5 个孩子。

也看看这个链接:xml count using php

【讨论】:

    【解决方案2】:

    尝试将foreach ($xml-&gt;alert-&gt;info[$i] as $entry) 替换为:

     foreach ($xml->alert->info[$i] as $j => $entry)
    

    当前项目索引将是$j

    【讨论】:

    • 是的,count() 很好
    【解决方案3】:

    你可能有点过于复杂了,因为它对你来说是新的。

    首先,您不需要像$xml-&gt;alert 这样引用alert 根元素,因为变量$xml 命名的SimpleXMLElement 代表该文档元素已经

    其次,这里不用数,直接foreach即可:

    foreach ($xml->info as $info) {
        echo ' * ', $info->asXML(), "\n";
    }
    

    这将遍历作为 alert 元素的子元素的三个 info 元素。

    我推荐Basic SimpleXML usage guide in the PHP manual 以获得 SimpleXML 的良好开端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2011-07-02
      • 2012-09-29
      • 1970-01-01
      • 2016-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多