json_decode - api 的问题

json_decode - issues with api

我正在尝试使用 api 查找某人在 twitch 上玩的游戏。我已经设置了 json_decode,它显示了 api 中的所有内容。但是,每当我尝试 print_r 游戏时,我都会收到错误消息。

错误:

Notice: Undefined property: stdClass::$game in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\Portfolio -- Website\twitchstreaminfo\streaminfo.php on line31

PHP代码:

$streamer = $_POST['username'];
$apiurl = "https://api.twitch.tv/kraken/streams/" . $streamer;
$apicontent = file_get_contents($apiurl);
$streamerinfo = json_decode($apicontent);
print_r($streamerinfo->game);

先尝试执行以下操作并验证结果:

print_r( $streamerinfo );

根据我对 API 的观察,以下应该有效:

print_r( $streamerinfo->stream->game );

您的错误是说“$game”的 属性 在对象“$streamerinfo”上不存在。如上所述,尝试打印“$streamerinfo”以验证它是否有效。您可以做的另一件事是添加以下内容:

if (isset($streamerinfo->game) {
     print_r($streamerinfo->game);
}

该代码可以防止此错误,但不能解决问题。我建议这是帮助您解决问题的最终解决方案

   if (isset($streamerinfo->game) {
     print_r($streamerinfo->game);
   } else {
     print_r($streamerinfo);
   }

这将使您的代码不会像现在这样中断。但是,如果失败,它也会打印“$streamerinfo”。这样你就可以看到它失败的原因。