Calvin Calvin - 13 days ago 7
JSON Question

Handle invalid Json responce from 3rd Paty

Working on a site and im hitting steams API to return a users inventory for thier CSGO items

this is the url i hit

$response = $this->guzzle->request('GET', "http://steamcommunity.com/profiles/{$communityId}/inventory/json/730/2");


So in dev/locally, it all works fine with the following

foreach (json_decode($response->getBody()->getContents(), true)['rgDescriptions'] as $item) {
$inventory[$item['name']] = $item;
}

return $inventory;


But when i updated my site it was complaining about an invalid argument for my foreach loop - after of var dumping - ($response->getBody()->getContents()) - only on the live site the json data that gets returned contains weird funky stuff - I'm new to json in general but it contains things like the following

"""
00006000\r\n
{"success":true,"rgInventory":{"8161072596":{"id":"8161072596","classid":"1560432042","instanceid":"480085569","amount":"1","pos":1},"8159918836":


and the end block like so

{"internal_name":"normal","name":"Normal","category":"Quality","category_name":"Category"},{"internal_name":"Rarity_Ancient","name":"Extraordinary","category":"Rarity","color":"eb4b4b","category_name":"Quality"}]}},"more":false,"more_start":false}\r\n
00000000\r\n
\r\n
"""


So this of course is why my foreach is breaking because my json_decode of the response will be returning null instead of an assoc array? (see full function at the bottom!)

I'm pretty sure that these are line breaks although I'm not sure? its rather annoying I'm not sure if I'm missing something on my side or its the response from steam although i fail to see how it is when i works fine on dev?

i also came across magic_quotes on research but i read they were depreciated in php 5.4? I'm running 5.6 so i can only think there must be something else server side that I'm missing?

here is my helper function below for reference

public function getCSGOInventory($communityId)
{
$response = $this->guzzle->request('GET', "http://steamcommunity.com/profiles/{$communityId}/inventory/json/730/2");

$inventory = [];
foreach (json_decode($response->getBody()->getContents(), true)['rgDescriptions'] as $item) {
$inventory[$item['name']] = $item;
}

return $inventory;
}

Answer

I had the same problem a while ago. The problem is the random numbers like 00000000 and 00006000 in your json code. This looks to be a bug in Guzzle. I was able to fix it by installing the php-curl package. Try performing an apt-get like this to fix the problem (if your on an OS like Ubuntu):

sudo apt-get install php-curl

You can find more about this here: https://github.com/guzzle/guzzle/issues/1385