简体   繁体   English

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

[英]PHP XML and nodes with same name

I am having some difficulty wrapping my brain around this, since I am new to PHP. 由于我是PHP的新手,因此我难以解决这个问题。

XML Document contains: XML文档包含:

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

And I can access The Owner Name via $current["OwnerDetails"]["Name"] ok 我可以通过$current["OwnerDetails"]["Name"]访问所有者名称,确定

However sometimes there are multiple ownerdetails: 但是,有时会有多个所有者详细信息:

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

I can use a 我可以用

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

and I see both names. 我看到两个名字。 But if there is only ONE OwnerDetails it won't display the name correctly.... How Do I reliably access this data even if I don't know if there will be one or multiple items? 但是,如果只有一个OwnerDetails,它将无法正确显示名称。...即使不知道会有一个还是多个项目,如何可靠地访问此数据?

The easiest way to deal with this might be something like the following, depending on your XML parsing library: 解决此问题的最简单方法可能如下所示,具体取决于您的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"];
}

However, SimpleXML can take care of this for you; 但是, SimpleXML可以为您解决这个问题。 SimpleXMLElement objects implement the Traversable interface, so you could use foreach in either scenario. SimpleXMLElement对象实现Traversable接口,因此您可以在两种情况下都使用foreach

I'm not sure what XML parsing function you're using, so it's hard to debug its precise behaviour. 我不确定您使用的是哪种XML解析功能,因此很难调试其准确的行为。

If you use SimpleXML , then foreach ( $current->OwnerDetails as $row ) should work in both cases. 如果使用SimpleXML ,则foreach ( $current->OwnerDetails as $row )在两种情况下均应起作用。 Similarly, both $current->OwnerDetails->Name and $current->OwnerDetails[0]->Name will get you the Name of the first child. 同样, $current->OwnerDetails->Name$current->OwnerDetails[0]->Name都将使您获得第一个孩子的Name SimpleXML overloads functionality to work smoothly in cases like this. 在这种情况下,SimpleXML重载功能以使其正常工作。

Note the -> notation (property access) to refer to a child node. 请注意->表示法(属性访问)引用一个子节点。 In SimpleXML, the ['string'] notation accesses attributes, eg $current->OwnerDetails['id'] . 在SimpleXML中, ['string']表示法访问属性,例如$current->OwnerDetails['id']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM