返回json PHP编码的问题是NULL

时间:2014-12-26 20:52:57

标签: php json webservice-client

我正在获取一个json字符串

$url = 'https://api.twitch.tv/kraken/channels/rootkitztv/follows';

并希望获取拥有个人资料照片的用户。那些不会返回'null'。

这是我的剧本

$ch = curl_init($url);                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);                                                         
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                                                                                                                                     

$followers_list = curl_exec($ch);   

$followers_result = json_decode($followers_list, true); 

    foreach ($followers_result as $data)
        {
         foreach ($data as $datas) {

        echo ("<img src=\"".$datas['user']['logo']."\"/>");

             }   
        }

当我运行它时,我会正确显示所有图像,但也会出现以下错误......

Warning: Invalid argument supplied for foreach() in /Library/WebServer/Documents/twitch/test.php on line 27

Warning: Illegal string offset 'user' in /Library/WebServer/Documents/twitch/test.php on line 30

Warning: Illegal string offset 'logo' in /Library/WebServer/Documents/twitch/test.php on line 30

Warning: Illegal string offset 'user' in /Library/WebServer/Documents/twitch/test.php on line 30

Warning: Illegal string offset 'logo' in /Library/WebServer/Documents/twitch/test.php on line 30

和2张图片在页面来源中显示为<img src="h"/>

我失去了这种情况,但也想知道这是否与某些徽标为空相关。不知道为什么我会收到这些错误。

1 个答案:

答案 0 :(得分:2)

如果您尝试获取徽标,那么您希望仅循环$followers_result['follows'] 。您还试图遍历"_total""_links"。这些没有['user']['logo']

foreach($followers_result['follows'] as $data){
    $logo = $data['user']['logo'];
    if($logo !== null){
        echo '<img src="'.$logo.'"/>';
    }
}