0

im getting this two errors: Notice: Trying to get property 'users' of non-object in /Applications/MAMP/htdocs/ig_stats/jsontest.php on line 5

Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/ig_stats/jsontest.php on line 5

Im trying:

$json = json_decode(file_get_contents('https://www.instagram.com/web/search/topsearch/?query=lol'));

foreach($json->users as $item)
{
    if($item->user->username == "lol")
    {
        echo $item->full_name;
    }
}

All i want is to get the data in 'full_name' from the 'user' 'lol'. But i dont know how i can search for it :/

Can someone give me a hint or a solution?

Elve Bi
  • 13
  • 2
  • @Jeff It's an object, he is not passing `TRUE` to the 2nd argument for `json_decode()`. – Spoody Apr 27 '18 at 20:31
  • yeah, I did a blind shot too quickly...my bad – Jeff Apr 27 '18 at 20:32
  • What is your PHP version? your code works fine for me (PHP 7) – Spoody Apr 27 '18 at 20:36
  • I cannot reproduce that error! _BUT_ `$item->full_name` should be `$item->user->full_name`. [See this fiddle](https://3v4l.org/cKJqr) (also for older versions) – Jeff Apr 27 '18 at 20:37
  • but in the json there are also 'places'. 'hashtags',.. not only users. maybe the error is related but somewhere else? – Jeff Apr 27 '18 at 20:42
  • @Jeff no it's not because he is only passing the `users` object, OP needs to be more active and reply. – Spoody Apr 27 '18 at 20:44
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – James Apr 27 '18 at 20:53
  • 1
    @Mehdi I know. But since the shown code didn't produce the shown error, there was a chance that some relevant code was hidden. – Jeff Apr 27 '18 at 21:01

1 Answers1

0

I'm not sure if there is a version where you can't iterate over an object, but if so, you can use the response as an array by passing TRUE to json_decode() like this:

$json = file_get_contents('https://www.instagram.com/web/search/topsearch/?query=lol');
$json = json_decode($json, TRUE);

foreach($json['users'] as $item)
{
    if($item['user']['username'] == "lol")
    {
        echo $item['user']['full_name'];
    }
}

You may want to debug your code, make sure the $json contains an object because your code works fine for me, this is what I tried:

$json = file_get_contents('https://www.instagram.com/web/search/topsearch/?query=lol');
$json = json_decode($json);

foreach($json->users as $item)
{
    if($item->user->username === 'lol'){
        echo $item->user->full_name; // You forgot the user part    
    }
}

Both Printed LOL.

Spoody
  • 2,852
  • 1
  • 26
  • 36
  • Thanks! Both worked fine for me. I was already on the way of the second one, but didnt finished it correctly :) – Elve Bi Apr 27 '18 at 20:58