DroidShare
DroidShare

Reputation: 30

Pulling certain information from Json

I've recently been exploring the Xbox API over at XboxAPI.com to try and increase my knowledge and confidence of actually using API's and also using Json Data. I found some code on another question that I had a play around with and got it to give me something back, the code I am currently using is:

$url     = 'https://xboxapi.com/v2/2745051201447500/presence';
$headers = array(
    'X-AUTH: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);

Visiting the page in the browser gives me the following:

{"xuid":2745051201447500,"state":"Online","devices":[{"type":"XboxOne","titles":[{"id":714681658,"name":"Home","placement":"Background","state":"Active","lastModified":"2014-10-07T22:02:34.821235Z"},{"id":446059611,"activity":{"richPresence":"In a Street Race."},"name":"Forza Horizon 2","placement":"Full","state":"Active","lastModified":"2014-10-07T22:02:34.821235Z"}]}]}

My question is, how do I pull certain bits of information out of the above? For example if I wanted to pull the "name" and just display that, how would I go about doing that? I've tried a couple of things including the following:

echo $result->devices[0]->type;

but that didn't work. I don't know how far off I am from the correct answer, but would appreciate any assistance.

Thanks

Upvotes: 0

Views: 53

Answers (3)

airtech
airtech

Reputation: 496

First, do a json_decode like below which will put into an associate array.

Then, you would need also to make sure you use an index on those that are multidimensional as noted below.

And voilla - basically, you're missing the json_decode.

$result = json_decode(curl_exec($ch));
$result->devices[0]->type;

Ugh - also forgot

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

You're curl is not outputting to a string variable.

Upvotes: 0

Forty3
Forty3

Reputation: 2229

I suspect you will need some akin to json_decode (http://php.net/manual/en/function.json-decode.php)

  :
$result = json_decode(curl_exec($ch);
echo $result->devices->titles->name;

Note: The above has not been tested.

Upvotes: 1

Marc B
Marc B

Reputation: 360672

devices is an array (note the [] in the JSON), so you need

$result->devices[0]->type // XboxOne
                ^^^

The same will hold for titles - that's also an array and would need [] dereferencing in PHP. a var_dump($result) would show you a nicely formatted structured dump of the array, and show you you exactly what "path" you need to use to get any to any piece of data in it.

Upvotes: 0

Related Questions