Search code examples
jsonwebapisteam

Print JSON array - steam web API


I've been toying around with the Steam Web API using JSON format. I've been trying to print the array output given by the API.

<?php
    $id = $_GET['id'];
    $key = 'xxx';
    
    $link = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . $key . '&steamids=' . $id . '&format=json');
    $profile_info = json_decode($link);
    
    $json_response = json_encode($profile_info->response);
    print($json_response['steamid']);
?>

The key is obviously replace by the key given to me by Steam's generator, but this code snippet I have only returns the character { it should return 76561197989628470 which is my steamid.

These are the arrays in JSON format

{    
   "response": {    
      "players": [    
         {    
            "steamid": "76561197989628470",    
            "communityvisibilitystate": 3,    
            "profilestate": 1,    
            "personaname": "Archey",    
            "lastlogoff": 1334719151,    
            "commentpermission": 1,    
            "profileurl": "http://steamcommunity.com/id/Archey6/",    
            "avatar": "http://media.steampowered.com/steamcommunity/public/images/avatars/74/745b633a08937a5cf52bb44c2bdd3552f85455d7.jpg",    
            "avatarmedium": "http://media.steampowered.com/steamcommunity/public/images/avatars/74/745b633a08937a5cf52bb44c2bdd3552f85455d7_medium.jpg",    
            "avatarfull": "http://media.steampowered.com/steamcommunity/public/images/avatars/74/745b633a08937a5cf52bb44c2bdd3552f85455d7_full.jpg",    
            "personastate": 1,    
            "primaryclanid": "103582791432066081",    
            "timecreated": 1177637717,    
            "loccountrycode": "CA",    
            "locstatecode": "SK"    
         }    
      ]    
   }

Solution

  • Why are you decoding then encoding json?

    <?php
        $id = $_GET['id'];
        $key = 'xxx';
    
        $link = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . $key . '&steamids=' . $id . '&format=json');
        $myarray = json_decode($link, true);
    
        print $myarray['response']['players'][0]['steamid'];
    ?>
    

    Or if you really need to encode again:

    <?php
        $id = $_GET['id'];
        $key = 'xxx';
    
        $link = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=' . $key . '&steamids=' . $id . '&format=json');
        $profile_info = json_decode($link);
    
        $json_response = json_encode($profile_info->response->players);
        $decoded = json_decode($json_response, true);
        print $json_response['steamid'];
    ?>