Facebook PHP API: Get the names of all your friends

If you didn’t already know, Facebook has an API that exposes quite a darn bit information. You can easily query this data using their API, but each request takes a fair bit of time. Typically, to get the names of all your friends, first you have to grab a list of the user ids of all your friends, and then query each and every single one to get their names. For me, that’s about 300 cross-server requests, which will almost certainly cause my server to time out, and probably force Facebook to reject me. Fortunately, Facebook has also created their own MySQL-like language, FQL (I pronounce it feequel), which lets you do some of these “complicated” queries in a single call. Here’s a simple example I wrote:

<?php
require_once 'facebook-platform/php/facebook.php';

$appapikey = 'yourapikeyhere';
$appsecret = 'yoursecretkey';
$facebook = new Facebook($appapikey, $appsecret);
$user_id = $facebook->require_login();

$result = fql_query('SELECT name FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=%s)', $user_id);
pr($result);


function fql_query($query) {
    global $facebook;
    $args = array_slice(func_get_args(), 1);
    return $facebook->api_client->fql_query(vsprintf($query, $args));
}

function pr($arr) {
    echo '<pre>';
    print_r($arr);
    echo '</pre>';
}

You’ll notice I’ve included two of my favorite wrapper functions. You can unroll them if you want. Anyway, just thought I’d share 🙂 I prefer writing FQL than trying to remember all their API calls anyway.

Oh… and just FYI, this prints out something like this:

Array
(
    [0] => Array
        (
            [name] => Mark Zuckerberg
        )

    [1] => Array
        (
            [name] => Tom Riddle
        )

I hate it when people leave it a mystery what exactly their example is doing!

Posted in

2 thoughts on “Facebook PHP API: Get the names of all your friends

Leave a Reply

Your email address will not be published. Required fields are marked *