I have a JSON like this:
{
"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
}
]
}
And I am trying to parse it like this:
$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'];
It doesn't return any values. Why is this?
It just returns:
IGN: Town Hall: Level: Trophies:
Use json_decode
with second parameter setting to true
will return Array
$data['avatar']
has sub array so you can access it whole sub array like
$data = json_decode($json,true);
$subarray = $data['avatar'][0];
echo $subarray['userName']; // King Shiv
See Demo
$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'];
Seems like you having a problem with the url. Tried with cURL and it returns "couldn't connect to host", which can be a firewall that blocks or something with your configuration. Your json decoding is fine, fix the problem with the address and you'll get the content.