Retrieving Facebook Open Graph Data with PHP

Ever wonder, “Huh, I have a company page on facebook, but DAMN it’s lame to have to login to se the stats”?  I did, and as always- let’s grab some data with PHP!


At the core of nearly anything you want to do with the facebook open graph is this url:

https://graph.facebook.com/(username or id)

And really, this doesn’t get a whole lot longer for the basics, we just need to use file_get_contents and json_decode functions to make some usable stuff from the data returned, we’ll get into the more complex stuff shortly, but for now…

$contents = file_get_contents( $url );
if( $contents )
    $data = json_decode( $contents, true );

And now we have a nice straightforward array of info from Facebook including:

  • id
  • about
  • cover => source (the image file)
  • likes
  • link
  • talking_about_count
  • website
  • and some other stuff that I just don’t care about all that much!

To see the full block of returned data, just run a quick pre output:

$url = 'https://graph.facebook.com/phpdevtips';
$contents = file_get_contents( $url );
if( $contents )
    $data = json_decode( $contents, true );
    echo '<pre>';
    print_r( $data );
    echo '</pre>';

Caching to Avoid Slow external requests

Since with the code above, every time you hit it, it’s requesting info from facebook that is (sorry to burst your bubble) unlikely to change more than a couple times a day, we can at least implement some basic $_SESSION based protocols to prevent the data from being requested more than hourly.

To do this without too much yelling and cursing (also for the sake of LOGIC), we need to drop this bad boy into a function.  And in keeping with that whole thing where we respect logic, we’ll call it “facebook_data” and give it some added params.

facebook_data( $username, $cache = true, $return = array() )

Furthermore, since I personally couldn’t try and actually care less about the function returning an image uri that I already have the image for, or the description I already have since I wrote it, we’ll set some defaults for what actually gets returned from this function using the $return parameter of the facebook_data function.

if( empty( $return ) )
    $return = array( 'likes', 'talking_about_count', 'cover', 'id', 'link', 'website' );

Now, granted- facebook doesn’t actually care- this $return array is more for the sake of YOU- the end user to prevent you from having to TOIL through the darkness that is totally useless crap (aka, we’ll use the array to return only matched values from the function and disregard the rest).

Now, be advised, I am skipping forward a bit to make this more on the “AH, that’s why that’s there” side (also, you can just go to the bottom and download this bad boy so it’s all good), so let’s jump to exactly HOW we’re going to prevent this thing from making a request to facebook every 15 seconds for no reason:

//It's appropriate to cache this data hourly (still need the date though)
$logged = date('Y-m-d h');

//Start a session to store the data if one isn't already
if( !session_id() )

And now that we’ve made sure we CAN store to a session, we’re going to make a bit of a nasty nested array of a $_SESSION variable, including one with the only purpose of telling us it’s already stored and active, but only after making sure we didn’t have one to begin with (deep breath after long sentence here).

//The session for the hour has already been stored, so we'll use that data
if( !empty( $_SESSION['fp_fb_sts'][$logged]['fp_fb_stored'] ) )
    $output = json_decode( $_SESSION['fp_fb_sts'][$logged]['fp_fb_dt'], true );
    $output['Facebook Data Cached'] = $logged .':00:00';
    return $output;

All we did in the codeblock above was check if our $logged variable assigned at the top had already been set to a session var, in which case we really (no really) don’t need to continue, we just need the data.

Otherwise we pull a…

    //Start over, the hour has expired
    unset( $_SESSION['fp_fb_sts'] );

    $contents = file_get_contents( $url );
    $data = json_decode( $contents, true );
    foreach( $data as $type => $value )
        //Cross reference our $return array for stuff we care about
        if( in_array( $type, $return ) )
            $output[$type] = $value;

    //Assign the session variables with the Y-m-d h (since hourly is kosher)
    $_SESSION['fp_fb_sts'][$logged]['fp_fb_stored'] = true;

    //Only the called variables are stored from the foreach above
    $_SESSION['fp_fb_sts'][$logged]['fp_fb_dt'] = json_encode( $output );
    return $output;

As I’m sure (if you’re paying attention) you noticed, when I specified the parameters for the function, there is indeed a $cache variable if for some reason you DO want to make totally unnecessary and repetitive external requests for the same data over and over and over and over and over, but that’s pretty much just a repeat of the elseblock above.


Since the data returned from the function is also in array format, you’ll need to call it like you want it. For example, if I want to know how many likes I have, and (for some reason) the url to the cover photo used, I’d say something like…

//Boom. Get the data based on the company page name
$data = facebook_data( 'yourawesomecompanypage' );

//Now make it mean something
echo 'This page has '. $data['likes'] .' likes!';
echo 'Cover image url: '.$data['cover']['source'];

Get the whole dealio

And that is enough from me! Download the script and do your thang!


Related Posts

4 Comments + Add Comment

  • Hi Bennett,

    It looks great and I would like to implement this into my website, but I can’t download the script. The link is not right. Could you please change that?


    • Link fixed- sorry about that!

  • is this work just by replacing the company name? we don’t want any auth or any other facebook files in our directory to first log us in and then get the data?
    i just replace the company name with my page WebSolOfficial but all in vain it just showed those errors
    Notice: Undefined index: likes in D:\xampp\htdocs\facebook-data\facebook-data\get-facebook-data.php on line 89
    This page has likes!

    Notice: Undefined index: cover in D:\xampp\htdocs\facebook-data\facebook-data\get-facebook-data.php on line 90
    Cover image:

Leave a comment