Dan Flood
Dan Flood

Reputation: 87

PHP XML and nodes with same name

I am having some difficulty wrapping my brain around this, since I am new to PHP.

XML Document contains:

<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

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?

Upvotes: 1

Views: 3798

Answers (2)

cmbuckley
cmbuckley

Reputation: 42458

The easiest way to deal with this might be something like the following, depending on your XML parsing library:

// 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; SimpleXMLElement objects implement the Traversable interface, so you could use foreach in either scenario.

Upvotes: 3

IMSoP
IMSoP

Reputation: 97718

I'm not sure what XML parsing function you're using, so it's hard to debug its precise behaviour.

If you use SimpleXML, then foreach ( $current->OwnerDetails as $row ) should work in both cases. Similarly, both $current->OwnerDetails->Name and $current->OwnerDetails[0]->Name will get you the Name of the first child. SimpleXML overloads functionality to work smoothly in cases like this.

Note the -> notation (property access) to refer to a child node. In SimpleXML, the ['string'] notation accesses attributes, e.g. $current->OwnerDetails['id'].

Upvotes: 1

Related Questions