我正在尝试运行此 PHP 文件,但不断收到类似错误
Undefined property: stdClass::$games
和
Invalid argument supplied for foreach()
这是错误的图片http://imageshack.us/a/img845/6270/34356212.jpg下面是我正在运行的脚本,减去我的 Steam API key 。
<?php
$api_key = '........'; //Steam API Key, Required to work
$lines = file('parse1.txt'); //reads in the file with the list of user numbers
$game_id = 550; //Steam Game ID, 440 is TF2
foreach ($lines as $usernumber) { //loops line by line
$link = 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=' . $api_key . '&steamid=' . $usernumber . '&format=json';
$json = file_get_contents($link); //Reads link (this ^)
$data = json_decode($json);
foreach ($data->response->games as $game) {
if ($game->appid == $game_id) {
$playtime = $game->playtime_forever;
if (($playtime < 5400) && ($playtime > 1)) {
//echo 'Playtime for ', $usernumber, ' is ' . $playtime."<br>";
echo $usernumber."<br>";
}
}
}
}
?>
Parse.txt包含steam ID,例如(76561197987683795、76561198063283029) 我认为它与嵌套 IF 命令有关,但我不知道我错过了什么,任何帮助都会很大!谢谢
最佳答案
json 中的 response
对象不包含 games
数组。
您需要为代码添加更多防御措施,以处理外部数据不符合预期的情况:
if (!empty($data->response->games)) {
foreach ($data->response->games as $game) {
if ($game->appid == $game_id) {
$playtime = $game->playtime_forever;
if (($playtime < 5400) && ($playtime > 1)) {
//echo 'Playtime for ', $usernumber, ' is ' . $playtime."<br>";
echo $usernumber."<br>";
}
}
}
}
} else {
echo 'Games missing!';
}
关于PHP 脚本未定义属性和无效参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16114254/