Json解码 - PHP

时间:2017-02-18 13:25:58

标签: php json steam-web-api

我正在尝试从一个API解码json,但是当我尝试代码时:

 <?php
   $json = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=270EBE5B0B2501EE0FC750196325406B&steamids=76561198260508210");
   $decode = json_decode($json,1);
   echo $decode['realname'];
  ?>

出现:

Notice: Undefined index: realname in C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www\CSGrow\index.php on line 26

2 个答案:

答案 0 :(得分:1)

这是因为 realname 不在数组的主要部分。你应该这样看:

json -> "response" -> "players"[0] -> "realname"

所以你需要做这样的事情:

$realname = $decode->response->players[0]->realname;

答案 1 :(得分:1)

当你仔细检查API响应时,那就是返回的值:

{
  "response": {
    "players": [
      {
        "steamid": "76561198260508210",
        "communityvisibilitystate": 3,
        "profilestate": 1,
        "personaname": "xGrow ◔ ⌣ ◔",
        "lastlogoff": 1487378601,
        "commentpermission": 1,
        "profileurl": "http://steamcommunity.com/id/xgrow/",
        "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/9b/9bc4b0e198dfcc919cbcc781beb5886acaa9daee.jpg",
        "avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/9b/9bc4b0e198dfcc919cbcc781beb5886acaa9daee_medium.jpg",
        "avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/9b/9bc4b0e198dfcc919cbcc781beb5886acaa9daee_full.jpg",
        "personastate": 1,
        "realname": "Pedro",
        "primaryclanid": "103582791434436747",
        "timecreated": 1447526746,
        "personastateflags": 0,
        "loccountrycode": "PT"
      }
     ]
   }
}

要创建一个玩家对象,请按以下代码进行编码:

<?php $json = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=270EBE5B0B2501EE0FC750196325406B&steamids=76561198260508210");
 $decode = json_decode($json,1);

 $player = $decode['response']['players'][0];

 echo $player['realname'];
?>