0

I am trying to access the steamid data in a json response returned by an API, specifically the Steam API.

The responses look like this:

enter image description here

I've made it return json but why do I see array all over the place?

How would I access the steamid data? I'm getting a bit confused as I thought this would be json.

I'm using guzzle to get the data and converting it to json using the guzzle json() method:

enter image description here

Any help would be appreciated.

Thanks!

1 Answer 1

1

The API is indeed using JSON to send/receive , however JSON is just a string, so in order to use that data PHP must parse it, which is automatically handled by guzzle, so as soon as you get the data back it has automatically decoded the data into a usable format for yourself.

It does this using the json_encode() and json_decode() functions.

You'd be able to access the steamid with the following.

// Assuming $data is your response from the API.
$players = array_get($data, 'response.players', []);

foreach($players as $player)
{
    $steamId = array_get($player, 'steamid', null);
}

Using the laravel helper array_get() function is a great way of ensuring you return a sane default if the data doesn't exist as well as eliminating the need to keep doing things like isset() to avoid errors about undefined indexes, etc. http://laravel.com/docs/5.1/helpers

Alternativly not using the laravel helpers you could use something similar to below, although I'd advise you add checks to avoid the aforementioned problems.

foreach($data['response']['players'] as $player)
{
    $steamId = $player['steamid'];
}

If you didn't want guzzle to automatically decode the API's JSON I believe you should just be able to call the getBody() method to return the JSON string.

$json = $response->getBody();
Sign up to request clarification or add additional context in comments.

2 Comments

Beautiful answer! Is there an easier way to get the SteamID if I'm sure there will only be 1 player returned? Or would the foreach still be the best method?
If theres only ever going to be one player then you could just do $steamId = array_get($data, 'response.players.0.steamid', null);. Using the 'dot notation' you should be able to access any level of the array using the array helper functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.