PHP嵌套foreach访问xml元素

PHP嵌套foreach访问xml元素,php,xml,Php,Xml,我需要使用PHP访问存储在.XML文件中的数据 XML: SimpleXMLElement {#319 ▼ +"@attributes": array:3 [▶] +"suite": SimpleXMLElement {#329 ▼ +"@attributes": array:3 [▶] +"suite": array:4 [▼ 0 => SimpleXMLElement

我需要使用PHP访问存储在.XML文件中的数据

XML: 

SimpleXMLElement {#319 ▼
  +"@attributes": array:3 [▶]
  +"suite": SimpleXMLElement {#329 ▼
    +"@attributes": array:3 [▶]
    +"suite": array:4 [▼
      0 => SimpleXMLElement {#332 ▼
        +"@attributes": array:3 [▶]
        +"test": SimpleXMLElement {#347 ▶}
        +"status": SimpleXMLElement {#348 ▶}
      }
      1 => SimpleXMLElement {#333 ▶}
      2 => SimpleXMLElement {#334 ▶}
      3 => SimpleXMLElement {#335 ▶}
    ]
    +"status": SimpleXMLElement {#336 ▶}
  }
  +"statistics": SimpleXMLElement {#330 ▶}
  +"errors": SimpleXMLElement {#331}
}
我想要访问suite->suite中名为test的每个元素:

foreach($sxml->suite->suite as $name => $f) {
      $feature_name = $f['name'];
        foreach($sxml->suite->suite->test as $name => $t) {
          $test_name = $t['name'];
      
  }}
上面的代码为每个特性提供了相同的测试,而不是该特性的实际测试

当前

特征1 测试1 专题2 测试1

预期的

特征1 测试1 专题2 测试2


在输出中,我看到的是每个功能的相同测试,而不是每个功能的每个测试。这个问题的答案可以在这里的官方文档中找到:

在我的例子中,解决方法是:

foreach ($sxml->children() as $req) {
        foreach ($req->children() as $feat) {
            foreach ($feat->children() as $test) {
            }
        }
    }

SimpleXMLElement标记属性的行为因访问方式而异

foreach($root->parent->item as$item)
将“parent”元素作为一个元素访问,它将返回第一个“parent”并忽略同级。“item”作为iterable(list)访问,因此它将返回所有“item”同级元素

要访问这两个as列表,您需要嵌套循环:

foreach ($sxml->suite as $parentSuite) {
   foreach ($parentSuite->suite as $suite) {
      foreach ($suite->test as $test) {
         var_dump($test);
      }
   }
}
或者使用Xpath表达式:

foreach ($sxml->xpath('suite/suite/test') as $test) {
    var_dump($test);
}

将相同的$test\u name变量分配给xml的所有元素,
$sxml->suite->suite->test
不是有效的路径(因为
$sxml->suite->suite
是一个数组)。您需要使用
$f
对象。@GiacomoM我现在明白了,谢谢you@Syscall这是有道理的,并引导我到php文档的正确页面,谢谢