Reputation: 103
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?
Upvotes: 1
Views: 83
Reputation: 89295
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
Upvotes: 1
Reputation: 2876
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 !
Upvotes: 0
Reputation: 1153
there are more Location so you have too loop on :
foreach ($hotel->Location as $l) {
if ("D5023" === $l->Identifier) {
var_dump($l->Availability->Rooms);
}
}
Upvotes: 0