up vote 2 down vote favorite
<?php
$handle = fopen("https://graph.facebook.com/[email protected]&type=user&access_token=2227472222|2.mLWDqcUsekDYK_FQQXYnHw__.3600.1279803900-100001310000000|YxS1eGhjx2rpNYzzzzzzzLrfb5hMc.", "rb");
$json = stream_get_contents($handle);
fclose($handle);
echo $json;
$obj = json_decode($json);
print $obj->{'id'};
?>

Here is the JSON: {"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}

It echos the JSON but I was unable to print the id.

Also I tried:

<?php
$obj = json_decode($json);
$obj = $obj->{'data'};
print $obj->{'id'};
?>
link|flag

2  
a) Instead of fopen/stream_get_contents/fclose, why not use $json = file_get_contents($url);? b) Have a look at var_dump($obj), maybe it'll help. – nikic Jul 22 at 12:17

5 Answers

up vote 1 down vote accepted

data is an array, so it should be:

print $obj[0]->{'id'};
link|flag
up vote 3 down vote

It looks like the key "data" is an array of objects, so this should work:

$obj = json_decode($json);
echo $obj->data[0]->name;
link|flag
up vote 3 down vote

Note that there is an array in the JSON.

{
    "data": [   // <--
      {
        "name": "Sinan \u00d6zcan",
        "id":   "610914868"
      }
    ]           // <--
}

You could try $obj = $obj->{'data'}[0] to get the first element in that array.

link|flag
up vote 2 down vote

Have you tried $obj->data or $obj->id?

Update: Others have noted that it should be $obj->data[0]->id and so on.

PS You may not want to include your private Facebook access tokens on a public website like SO...

link|flag
+1 for privacy warning. – yc Jul 22 at 14:09
up vote 1 down vote

It's a bit more complicated than that, when you get an associative array out of it:

$json = json_decode('{"data":[{"name":"Sinan \u00d6zcan","id":"610914868"}]}', true);

Then you may echo the id with:

var_dump($json['data'][0]['id']);

Without assoc, it has to be:

var_dump($json->data[0]->id);
link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.