Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use JSON objects from Facebook with PHP?

Tags:

json

php

facebook

http://developers.facebook.com/docs/reference/api/event

I'm trying to grab some values from a Facebook JSON even object in PHP. Namely, title of event, location, and people attending. Using the Graph API.

<?php

$jsonurl = "https://graph.facebook.com/331218348435?access_token=2227470867|2.rtBZMkVIVgKGZ7Xr4px3Dw__.3600.1280822400-662817093|apY_UHK_2SKQFel3XxpKJ09GEo4.";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json);

How can echo the values from JSON output? I'm assuming it will be returned as an array.

Thank you!

like image 871
maiko Avatar asked Aug 03 '10 08:08

maiko


2 Answers

If you're using PHP, you can use the PHP SDK to query the API. This means you can make calls like:

$user = $facebook->api('/someusername', array('fields' => 'id,first name,last_name ...'));

However, with your example, you could do the following:

$url  = "https://graph.facebook.com/331218348435?access_token=2227470867|2.rtBZMkVIVgKGZ7Xr4px3Dw__.3600.1280822400-662817093|apY_UHK_2SKQFel3XxpKJ09GEo4.";
$user = json_decode(file_get_contents($jsonurl));

echo $user['first_name'];

As if you use json_decode, it should decode the result into a native PHP array (or in same cases, an object).

like image 186
Martin Bean Avatar answered Oct 19 '22 13:10

Martin Bean


Specify the second argument of true to json_encode to convert it to array and then you can print the output like this:

$json_output = json_decode($json, true);
echo '<pre>';
print_r($json_output);
echo '</pre>';

Now you can get specific item like this:

echo $json_output['title'];
like image 36
Sarfraz Avatar answered Oct 19 '22 12:10

Sarfraz