user2151111
user2151111

Reputation: 5

How to read Facebook JSON results in PHP

Sorry - this will be a bit poorly worded.

My code fbid is from a form. I what to know how to get and display parts on whats been requested by file_get_contents().

<?php echo $_POST["fbid"]; ?>
<?php $x=$_POST['fbid'];?>
<?php echo file_get_contents("http://graph.facebook.com/" . $x); ?>

See the code below that's what the file_get_contents() displays like:

{
  "id": "4",
  "name": "Mark Zuckerberg",
  "first_name": "Mark",
  "last_name": "Zuckerberg",
  "link": "http:\/\/www.facebook.com\/zuck",
  "username": "zuck",
  "gender": "male",
  "locale": "en_US"
}

How can I echo the fields name and gender from this string?

Name: Their name 
Gender: Their gender

Upvotes: 0

Views: 5611

Answers (1)

hexacyanide
hexacyanide

Reputation: 91619

Use json_decode() to parse the data. The Facebook graph search results are returned in JSON format, so you just need to parse them and then they are accessible.

<?php

$data = file_get_contents("http://graph.facebook.com/" . $x);
$array = json_decode($data, true);

echo $array['name'];
echo $array['gender'];

?>

Take a look at the PHP manual.

Upvotes: 2

Related Questions