-1

Possible Duplicate:
How to get useful error messages in PHP?

I can't get this php json script to work. I'm trying to get the screen name from twitter, using their api.

Here's what I did.

$send_request = file_get_contents('https://api.twitter.com/1/users/lookup.json?screen_name=frankmeacey');

$request_contents = json_decode($send_request);

echo $request_contents->screen_name;

Why is this returning a blank value every time? I've tried changing things here and there and it's just not working...

Community
  • 1
  • 1
Frank
  • 1,844
  • 8
  • 29
  • 44
  • 1
    @hakre While the answer to that question would help solve this, they're hardly duplicates. By that logic, every question involving PHP errors is a duplicate of that question. – Barmar Oct 01 '12 at 17:48

5 Answers5

1

Because the data structure you get back is an array of objects, not an object.

echo $request_contents[0]->screen_name;
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

That data looks to be an object inside an array. Try

echo $request_contents[0]->screen_name;

Best to check first it is an array and to get the first user from it:

if (is_array($request_contents)) {
    $user_info = $request_contents[0];
}

if (isset($user_info)) {
    echo $user_info->screen_name;
}
Matt S
  • 14,976
  • 6
  • 57
  • 76
0

It's

$request_contents[0]->screen_name

since $request_contents is an array of objects, not the object itself.

Do a

var_dump($request_contents);

to see the structure of your json.

MiDo
  • 1,057
  • 1
  • 7
  • 11
0

try to use

print_r($request_contents); 

OR

var_dump($request_contents); 

for checking array.

Bot
  • 11,868
  • 11
  • 75
  • 131
Yogesh Suthar
  • 30,424
  • 18
  • 72
  • 100
0

Your page should not be blank .. you should get an error like Notice: Trying to get property of non-object in since you are calling $request_contents->screen_name which is not valid.

Try telling PHP to output all error Using

error_reporting(E_ALL);

I also prefer CURL its faster

$ch = curl_init("https://api.twitter.com/1/users/lookup.json?screen_name=frankmeacey");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);

$request_contents = json_decode($result);
var_dump($request_contents[0]->screen_name);

Output

 string 'frankmeacey' (length=11)
Baba
  • 94,024
  • 28
  • 166
  • 217