3

We need to update a somewhat old API a customer is using. We're getting the data with simplexml_load_file. The new structure is a bit more complex and I could not find a way to retrieve the new data.

The new structure looks like this:

enter image description here

Before we used $ratingPrice = $xml->hotel->ratingPrice; to get a value.

Now, I need to retrieve $xml->business->subcategoryRating->subcategoryRating->averageRating. I'm now stuck with that.

How am I able to get the average rating of wifi, or location and have them outputted in single variables?

Andreas
  • 412
  • 6
  • 19
  • Also, don't forget the `s` on the first `subcategoryRatings`. – Nomis Mar 23 '18 at 16:01
  • Possible duplicate of [How do you parse and process HTML/XML in PHP?](https://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – IncredibleHat Mar 23 '18 at 16:02
  • @IncredibleHat But how can I access a value directly? Lets say I just want Location, how would I do that? I cannot use [0], [1] etc for this. – Andreas Mar 23 '18 at 16:04

3 Answers3

1

If the order of your information is always the same (eg. Wi-Fi, Location, Apartment, Cleanliness) then you can do

$xml->business->subcategoryRating->subcategoryRating[x]->averageRating

so the x is the index of your xml list. Then

...subcategoryRating[0]->averageRating

corresponds to Wi-Fi and

...subcategoryRating[1]->averageRating

corresponds to Location and so forth.

Euclidian
  • 17
  • 4
0

You can extract the various ratings into an array and then use the relevant index to process the data your after. This uses the id attribute of the (for example) <category id="location"> element to use as the index...

$ratings = [];
foreach ( $xml->business->subcategoryRatings->subcategoryRating as $rating )    {
    $ratings[(string)$rating->category['id']] = (string)$rating->averageRating;
}

echo $ratings["location"].PHP_EOL;

This last line will need to be updated to access the particular element your after.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

As an alternative you could create an xpath expression and use xpath.

That would give you array of SimpleXMLElement objects.

$xml = simplexml_load_string($data);
$expression = '//business/subcategoryRatings/subcategoryRating[category[@id="wifi" or @id="location"]]';
foreach($xml->xpath($expression) as $item) {
    $averageRating = (string)$item->averageRating;    
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70