PHP XML和具有相同名称的节点

时间:2014-07-22 19:56:58

标签: php xml

由于我是PHP的新手,因此我在围绕这个问题时遇到了一些困难。

XML文档包含:

<containerDetails>
    <ID> theid </id>
     <OwnerDetails id = 23212>
          <name> the name </name>
     </OwnerDetails>
     <OtherData> 
           asdfdsa
     </OtherData>
</containerDetails>

我可以通过$current["OwnerDetails"]["Name"]确认

访问所有者姓名

但有时会有多个所有者详细信息:

<containerDetails>
    <ID> theid </id>
     <OwnerDetails id = 23212>
          <name> the name </name>
     </OwnerDetails>
     <OwnerDetails id = 23233>
          <name> other name </name>
     </OwnerDetails>
     <OtherData> 
           asdfdsa
     </OtherData>
</containerDetails>

我可以使用

foreach($current["OwnerDetails"] as $row) 
    echo $row["Name"]

我看到两个名字。但如果只有一个OwnerDetails,它就不会正确显示名称....即使我不知道是否会有一个或多个项目,我如何可靠地访问这些数据?

2 个答案:

答案 0 :(得分:3)

处理此问题的最简单方法可能类似于以下内容,具体取决于您的XML解析库:

// make sure you have an array containing OwnerDetails elements
$ownerDetails = isset($current["OwnerDetails"][0])
              ? $current["OwnerDetails"]
              : array($current["OwnerDetails"]);

// now iterate over it
foreach ($ownerDetails as $row) {
    echo $row["Name"];
}

但是,SimpleXML可以为您解决此问题; SimpleXMLElement对象实现了Traversable接口,因此您可以在任一场景中使用foreach

答案 1 :(得分:1)

我不确定您正在使用什么XML解析功能,因此很难调整其精确行为。

如果您使用SimpleXML,那么foreach ( $current->OwnerDetails as $row )应该适用于这两种情况。同样,$current->OwnerDetails->Name$current->OwnerDetails[0]->Name都可以获得第一个孩子的Name。 SimpleXML重载功能可以在这种情况下顺利运行。

请注意->表示法(属性访问权限)以引用子节点。在SimpleXML中,['string']表示法访问属性,例如$current->OwnerDetails['id']

相关问题