-1

I am fetching a json string

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

and want to fetch the users who have a profile pic. Those don't it returns as 'null'.

Here is my script

$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']."\"/>");

             }   
        }

When I run it I get all the images displaying properly but also the following errors...

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

and 2 images come through as <img src="h"/> in the page source.

Im lost as where this happens but also wondering if this is related to some logos being null. Not sure why I am getting these errors.

Daniel Alder
  • 5,031
  • 2
  • 45
  • 55
ServerSideSkittles
  • 2,713
  • 10
  • 34
  • 60
  • Take a look at the JSON you are getting back (try to `var_dump($followers_result);`). `$followers_result` is an array with 3 keys: `"follows"`, `"_total"` and `"_links"`. (Note that ``"_total"`` isn't an array) – gen_Eric Dec 26 '14 at 20:58
  • Here is the result I am getting back http://pastie.org/private/ya2qqtamk60kpd8iffegww and yes the result is an array with 3 keys, but how do I fix this? I am confused why its saying this when I specify just the logo in the foreach loop. – ServerSideSkittles Dec 26 '14 at 21:21

1 Answers1

2

If you are trying to get the logos, then you want to be looping over $followers_result['follows'] only. You were trying to loop over "_total" and "_links" as well. These don't have ['user']['logo'].

foreach($followers_result['follows'] as $data){
    $logo = $data['user']['logo'];
    if($logo !== null){
        echo '<img src="'.$logo.'"/>';
    }
}
gen_Eric
  • 223,194
  • 41
  • 299
  • 337