PHP 脚本未定义属性和无效参数错误

标签 php

我正在尝试运行此 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/

相关文章:

php - 在 Ratchet 的 MessageComponentInterface 中访问 Eloquent ORM

php - PHP解析/语法错误;以及如何解决它们

php - WooCommerce 编辑帐户抛出 'display name is a required field' 错误

PHP redis 错误

PHP mySQL 查询和 PHP 变量

php - 如何在 codeigniter 的语言文件中使用带变量的字符串?

php - simpleXml 到数组的行为对我来说很奇怪,并且在 9941 项处中断

php - 如何在没有 cURL 的情况下从 HTTPS 连接获取 XML?

php - 如何在MySQL中使用LIKE?

php - 如何更改 Zend Studio 中的默认工作区位置?