4
<?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'};
?>
1
  • 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. Commented Jul 22, 2010 at 12:17

5 Answers 5

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

data is an array, so it should be:

print $obj[0]->{'id'};

Comments

3

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

$obj = json_decode($json);
echo $obj->data[0]->name;

Comments

2

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

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.