1

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?

michi
  • 6,565
  • 4
  • 33
  • 56
Kaspar
  • 107
  • 1
  • 6
  • 1
    not sure, do you mean PHP's simpleXML? Or is there XMLsimple for PHP as well? please clarify! – michi Jun 13 '15 at 13:07

3 Answers3

1

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

har07
  • 88,338
  • 12
  • 84
  • 137
0

there are more Location so you have too loop on :

foreach ($hotel->Location as $l) {
    if ("D5023" === $l->Identifier) {
        var_dump($l->Availability->Rooms);
    }
}
mmm
  • 1,070
  • 1
  • 7
  • 15
0

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 !

Nassim
  • 2,879
  • 2
  • 37
  • 39