简体   繁体   中英

Steam API JSON returning bad request 400 only when empty

Working with Steam API, I'm stuck with the following problem: when trying to get player achievements , it's perfect - when it's returing results , something like this:

{
   "playerstats":{
      "steamID":"xxxxxxxxxxxxxxxxx",
      "gameName":"Life is Strange™",
      "achievements":[
         {
            "apiname":"AC_1",
            "achieved":1,
            "unlocktime":1620689085
         },
         {
            "apiname":"AC_2",
            "achieved":1,
            "unlocktime":1620677605
         },
         /* ETC, ETC...  */
         {
            "apiname":"AC_60",
            "achieved":0,
            "unlocktime":0
         }
      ],
      "success":true
   }
}

But in some cases, a product can return empty, because it doesn't have achievements, like this:

{
   "playerstats":{
      "error":"Requested app has no stats",
      "success":false
   }
}

And then I get an error Bad Request 400 for the file_get_contents.

My code is:

$json_achv = file_get_contents('https://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?appid='. $the_appid .'&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&steamid='. $steam_userid);
$data_jprog = json_decode($json_achv,true);

I have tried this , same result (Bad Request 400). And using curl , the json_decode returns NULL.

Any thoughts?

After a few more tests, I found the 400 Bad Request was related to UTF8 error. Unable to modify headers, I made the file_get_contents ignore errors .

$the_json = 'https://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?appid='. $the_appid.'&key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&steamid='. $steam_userid;
$context = stream_context_create(array('http' => array('ignore_errors' => true)));
$json_achv = file_get_contents($the_json, false, $context);
$data_jprog = json_decode($json_achv,true);

Now I can test the "success" true or false.

if ($data_jprog['playerstats']['success'] !== true) {
 echo 'no achievements';
}
else {
 echo 'Total achievements'. count($data_jprog['playerstats']['achievements']);
 // blabla whatever you want to do 
}  

I'm not sure why I tried it before and it failed, but it's working now. Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM