简体   繁体   中英

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?

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

there are more Location so you have too loop on :

foreach ($hotel->Location as $l) {
    if ("D5023" === $l->Identifier) {
        var_dump($l->Availability->Rooms);
    }
}

you load your file and loop through the XML file and check the ID , don't forget to cast the xml from object to string so you can compare 2 strings to each other and not an object to a string.

if( $xml = simplexml_load_file("path_to_xml.xml",'SimpleXMLElement', LIBXML_NOWARNING) ) 
        {
            echo("File loaded ...");

            // loop through XML 
            foreach ($xml->hotel as $hotel)
            { 
                // convert the xml object to a string and compare it with the room ID
                if((string)$hotel->Location->Identifier == "D5023")
                {
                    echo("there are ".$hotel->Location->Availability->Rooms."Available room in this hotel");
                }
            }
        }
        else
        echo("error loading file!");

hope that helps !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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