Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
<?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'};
?>
share|improve this question
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 '10 at 12:17

5 Answers

up vote 3 down vote accepted

data is an array, so it should be:

print $obj[0]->{'id'};
share|improve this answer

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.

share|improve this answer

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

$obj = json_decode($json);
echo $obj->data[0]->name;
share|improve this answer

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...

share|improve this answer
+1 for privacy warning. – yahelc Jul 22 '10 at 14:09

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);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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