Search code examples
phpxmlxml-simple

XMLsimple get value of next element


This is a small part of the XML file I am reading:

<hotel>    
<Location>
    <Identifier>D5023</Identifier>
    <IsAvailable>true</IsAvailable>
    <Availability>
        <TimeStamp>2015-06-11T16:04:23.887</TimeStamp>
        <Rooms>525</Rooms>
        <Beds>845</Beds>
    </Availability>
</Location>
<Location>
    ect.
</Location>
</hotel>

Using XMLsimple I want to get the number of available rooms for location D5023 (and other locations). But because the Identifier is a child from the Location attribute I am struggling to get the right data.

This is what I came up with, but obviously this doesnt work

$hotel->Location->Identifier['D5023']->Availability->Rooms;

How can I get this right?


Solution

  • You can use SimpleXMLElement::xpath() to get specific part of XML by complex criteria, for example :

    $xml = <<<XML
    <hotel>    
    <Location>
        <Identifier>D5023</Identifier>
        <IsAvailable>true</IsAvailable>
        <Availability>
            <TimeStamp>2015-06-11T16:04:23.887</TimeStamp>
            <Rooms>525</Rooms>
            <Beds>845</Beds>
        </Availability>
    </Location>
    <Location>
        ect.
    </Location>
    </hotel>
    XML;
    $hotel = new SimpleXMLElement($xml);
    $result = $hotel->xpath("/hotel/Location[Identifier='D5023']/Availability/Rooms")[0];
    echo $result;
    

    output :

    525
    

    Demo