无法从php解析json

时间:2015-10-04 06:43:23

标签: php json

我有一个像这样的JSON:

{
  "avatar": [
    {
      "Trophies": 1022,
      "clanLevel": 1,
      "Attack K Factor": -1921682810,
      "Attacks Won": 1,
      "freeGems": -1916837036,
      "clanBadge": 0,
      "clanCaslteLevel": 5,
      "currentHomeId": 12888426248,
      "clanRole": 2,
      "exp": 5013,
      "homeId": 12888426248,
      "Attacks Lost": -1307141699,
      "clanId": 326417604098,
      "boughtGems": -1517098100,
      "userNameChange": false,
      "numOfNameChanges": 0,
      "level": 111,
      "league": 5,
      "userName": "King Shiv",
      "nameTag": 1440968203000,
      "clanName": "lol",
      "Defenses Won": 17,
      "maxCcTroops": 30,
      "gems": -1370568149,
      "Defenses Lost": -2055915376,
      "townHall": 9,
      "inWar": 1,
      "Attack Rating": -1000115629
    }
  ]
}

我试图像这样解析它:

$url = "http://185.112.249.77:9999/Api/Player?player=1;
$url = preg_replace("/ /", "%20", $url);
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
echo "IGN: ".$data['avatar']['userName'];
echo "<br />Town Hall: ".$data['avatar']['townHallLevel'];
echo "<br />Level: ".$data['avatar']['level'];
echo "<br />Trophies: ".$data['avatar']['trophies'];
echo "<br />".$data['avatar']['clanRole'];

它不会返回任何值。这是为什么?

它只会返回:

IGN: 市政厅: 水平: 奖杯:

3 个答案:

答案 0 :(得分:0)

使用json_decode第二个参数设置true会返回Array $data['avatar']有子数组,因此您可以像

一样访问整个子数组
$data = json_decode($json,true);
$subarray = $data['avatar'][0];
echo $subarray['userName']; // King Shiv

请参阅Demo

答案 1 :(得分:0)

$url = "http://185.112.249.77:9999/Api/Player?player=1;
                                                     //^ you forgot to close with "
                                                 //That's why it cant parse your data

$url = preg_replace("/ /", "%20", $url);
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
echo "IGN: ".$data['avatar'][0]['userName']; // [0] here is the first index
echo "<br />Town Hall: ".$data['avatar'][0]['townHall'];
echo "<br />Level: ".$data['avatar'][0]['level'];
echo "<br />Trophies: ".$data['avatar'][0]['Trophies'];
echo "<br />".$data['avatar'][0]['clanRole'];

答案 2 :(得分:0)

好像你的网址有问题。尝试使用cURL并返回“无法连接到主机”,这可能是阻止或配置您的配置的防火墙。你的json解码很好,解决了地址问题,你就会得到内容。