Website Facebook feed, take 2 a more robust way!?

In a previous post we walked through a way to get a Facebook feed onto your site.

This post is about a more robust(?) way to get the work done!

This solution always provides you with a valid access token. You don’t have to create one yourself.

First the code and the walkthrough below.

$app_id = 'APP_ID';
$app_secret = 'APP_SECRET';
$my_url = 'http://localhost:8888/Facebook/FQL';
$page_id = '164076286984711';

$token_url = 'https://graph.facebook.com/oauth/access_token?client_id='
  . $app_id . '&redirect_uri=' . urlencode($my_url) 
  . '&client_secret=' . $app_secret 
  . '&grant_type=client_credentials';

$access_token = substr(file_get_contents($token_url), 13);

$fql_query_url = 'https://graph.facebook.com/'
  . 'fql?q=SELECT+message,attachment+FROM+stream+WHERE+source_id=' . $page_id
  . '&access_token=' . $access_token;
$fql_query_result = file_get_contents($fql_query_url);
$fql_query_obj = json_decode($fql_query_result, true);

Line 1 – 4: Fill in your app id, app secret, the redirect url and the page id you want the feed from.

Line 6 – 9: Here we get an access token (app token) with grant type of client_credentials. Read more about Facebook access tokens.

On line 13 – 16 we query the Facebook graph API to get the data from our page. We use FQL to fetch the result. Read more about FQL and what data to get from the tables.

Line 17 then JSON-decodes the response in an array.

Output the data

<?php foreach ( $fql_query_obj['data'] as $data ) : ?>
  <div class="message">
    <p><?php echo $data['message']; ?></p>
    <?php $images = @$data['attachment']['media']; ?>
    <?php if ( $images ) : ?>
      <?php foreach ( $images as $image ) : ?>
        <p><img src="<?php echo $image['photo']['images'][1]['src']; ?>" /></p>
      <?php endforeach; ?>
    <?php endif; ?>
  </div>
<?php endforeach; ?>

We run through the data with foreach.

On line 4 we get any attachments and suppress any warnings/notices with the @-sign (@$data).

We then run a inline foreach to get all the attachments (only photos in this case) and echos out the src for the image. Note that the [1] on line 7 gets the second element in the array. Without any deeper investigation I believe you get the largest image. The first element is the small (_s), thumb. (See below for an alternative solution).

Alternative image solution

In the $image object there is ‘src’ ($image[‘src’]), where you get the small source (_s). You can then use the same replace-method in the previous post to get the normal (_n) one.

Source on git

Comments are closed.