2

我正在尝试运行这个 PHP 文件,但我不断收到类似的错误

Undefined property: stdClass::$games

Invalid argument supplied for foreach()

这是错误http://imageshack.us/a/img845/6270/34356212.jpg的图片,下面是我正在运行的脚本减去我的 Steam API 密钥。

<?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 包含蒸汽 ID,例如(76561197987683795、76561198063283029)我认为它与嵌套的 IF 命令有关,但我不知道我缺少什么,任何帮助都会很大!谢谢

4

2 回答 2

2

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!';
}
于 2013-04-19T22:16:25.357 回答
0
$data->response->games

您的 JSON 响应中似乎不存在此密钥。json_decode尝试通过在调用后编写来自己调试它: var_dump($data->response);. 这应该可以帮助您了解这里出了什么问题。

于 2013-04-19T22:16:35.453 回答