19

I would like to know how is it possible to retrieve a string from an external page.

For example: In a PHP website, the user sends a facebook id, ex: 1157251270

And the website returns the name from http://graph.facebook.com/1157251270.

I hope I made it clear.

Thank you

Gordon
  • 312,688
  • 75
  • 539
  • 559
John Doe
  • 225
  • 2
  • 3
  • 5
  • 1
    *(related)* [Stuck on Graph API (facebook API), how do i get name, email and sex using this code?](http://stackoverflow.com/questions/4093548/stuck-on-graph-api-facebook-api-how-do-i-get-name-email-and-sex-using-this-co) – Gordon Apr 26 '11 at 10:31
  • (related) [What is JSON and why would I use it?](http://stackoverflow.com/questions/383692/what-is-json-and-why-would-i-use-it) – Gordon Apr 26 '11 at 10:32
  • I would read the Facebook TOS for this, just to be clear if your activity is legal. – ifaour Apr 26 '11 at 10:48

5 Answers5

26

The Graph API returns JSON strings, so you can use:

echo json_decode(file_get_contents('http://graph.facebook.com/1157251270'))->name;

or more verbose:

$pageContent = file_get_contents('http://graph.facebook.com/1157251270');
$parsedJson  = json_decode($pageContent);
echo $parsedJson->name; // Romanos Fessas

See json_decode — Decodes a JSON string

Gordon
  • 312,688
  • 75
  • 539
  • 559
6

If you are using Facebook's PHP SDK, you can also do this to query their graph API:

$fb = new Facebook();
$object = $fb->api('/1157251270');
jesal
  • 7,852
  • 6
  • 50
  • 56
5

you get it by:

$link = json_decode(file_get_contents('http://graph.facebook.com/1157251270'));
echo $link->name;

Nice tut: http://webhole.net/2009/08/31/how-to-read-json-data-with-php/

Adnan
  • 25,882
  • 18
  • 81
  • 110
2

Either you use :

$res_json = file_gets_contents("http://graph.facebook.com/1157251270")
$res = json_decode($res_json)

Or, if you prefer curl (here with https and access token) :

$ch4 = curl_init();
curl_setopt($ch4, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch4, CURLOPT_URL, "https://graph.facebook.com/1157251270?access_token=YOUR_ACCESS_TOKEN");
curl_setopt($ch4, CURLOPT_SSL_VERIFYPEER, false);

if(!$result = curl_exec($ch4))
{
    echo curl_error($ch4);
} else {
    $res = json_decode($res_json)
}

curl_close($ch4);
dwarfy
  • 3,076
  • 18
  • 22
  • If you require non-public information you will have to ask the user for permission, then use an access_token to view its informations – dwarfy Apr 26 '11 at 10:34
0

For facebook data you can use json_decode.

For another sites try with webscraping, for example: here

Gordon
  • 312,688
  • 75
  • 539
  • 559
Mateo
  • 177
  • 2
  • 8