After having written a working pure PHP code to fetch and parse both Twitter tweets and general RSS feeds such as WordPress blogs, I was curious of how I could do the same with another popular social media, Facebook. Just as the other two I’m interested in writing a code simple as possible with no additional libraries, scripts or software that needs to be installed, and no JavaScript.

Writing a feed parser for Facebook turned out being a little trickier than Twitter or for general purposes. First of all I was looking for status updates only, not anything else, such as people “liking” stuff, comments, activities such as games, wall posts and so forth. It’s really a matter of privacy. You wouldn’t want your name or comment to be displayed for the public on your unknown friend’s friend’s blog, would you? So in a way Facebook status updats only becomes like Twitter, a channel that displays your latest thoughts or happenings. But with good help of time, Googling and pieces from here and there, I have assembled and now sharing a working pure PHP feed parser that fetches and displays your Facebook status updates.

Again, this is meant as a guide for people who are looking for something as simple as this, or a pointer on the way for someone who want to create a more complex feed parser for social medias. This tutorial is targeted for people who know some PHP beforehand, and covers one method of many. The code is as simple as it gets, I wanted to emphasize the skeleton of a Facebook feed parser by including only the absolutely necessary things that needs to be included, excluding things such as error handling. I would also like you to take the time to read through the code and write it out yourselves, not just copy-paste. This way it’s easier to customize it to your liking, and you learn more.

Just like Twitter, Facebook also offer Facebook badges, which is an easier way to display your Facebook profile. With Facebook’s badge system you can customize a box that displays your current profile picture, current status, and types of info that exist in your profile, and put the badge wherever you want it on your site. But the Facebook badge can only display your current status updates, not the previous ones. I simply wanted something that displays the last 3 or 5 status updates, so a Facebook badge was not an option. Now, let’s get started!

But before you can start you need the URL to your Facebook status updates. This is not a straightforward task, so I’ve added a guide to help you find it. Click on the images to see a larger version.

How to find your Facebook status updates RSS URL

Log on Facebook and look at the very top. Next to Facebook’s logo there are three buttons, Friend Requests, Messages and Notifications. Click on Notifications, which opens a fly-out containing the last notifications. On the bottom there is a link “See all notifications”. Click on this.

This brings you to a page with your notifications, but what we’re after is in the menu on the right hand. On the bottom there is a RSS icon with the text “Via RSS”. Update (13.10.2010): The RSS icon with the text “Via RSS” is now located at the very top of the Notifications page. Click on this and it brings you to a RSS feed. But this is not quite what we’re looking for. This feed is either empty or contains all kind of notifications, other people commenting on your stuff, wall posts, and you commenting others. Your status updates are not included! But no worries, you are only one step away from finding your URL. Look at your browser’s address bar. Look for the word "notification".

Recplace the word "notifications" with the word "status" (without the double quotes) and press Enter. Your browser should now display a feed with your status updates only. Great, we have the URL! Copy the URL and let’s get started with the PHP feed parser.

PHP function to fetch your Facebook status updates

I’ve placed the parser inside a PHP function for simpleness’ and tidiness’ sake. Place this function in the beginning of your site’s files, or if you have, inside a functions.php file. The function takes two arguments: the URL as a string and the number of updates you want to fetch as an integer, in that order. Error handling code to check for e.g. the validity or type of arguments is not included, so be sure you get the arguments and their types right, or add an error handling code yourself. This code extracts the RSS2.0 fields description (the status update text), pubDate (date it was posted) and link (link to the status update in Facebook), but you can add or remove fields as you wish. Take a look at what kind of fields you have in your feed.

As for data handling, this code checks the Facebook status update for a hyperlink (starting with <a href="), which is a link to another Facebook profile (the user has referred a friend using @). But the thing is, the Facebook feed assume you’re clicking this link from inside Facebook and therefore the link has not got the preceding “http://www.facebook.com”. So I add this string in the beginning of the link’s href so it works correctly from anywhere. Then it converts the status into ISO-8859-1 in order to display special symbols correctly, targeted for non-english Facebook users (such as myself). You can edit the date and time format (marked with red underscore below) to your liking, the one below is what I prefer (refer to the manual for PHP date if you’re unsure).

<?php
function fetch_fb_feed($url, $maxnumber) {
     /* The following line is absolutely necessary to read Facebook feeds. Facebook will not recognize PHP as a browser and therefore won't fetch anything. So we define a browser here */  
     ini_set('user_agent', 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3');

     $updates = simplexml_load_file($url);  //Load feed with simplexml

     $fb_array = array();  //Initialize empty array to store statuses
     foreach ($updates->channel->item as $fb_update) {
          if ($maxnumber == 0) {
               break;
          } else {
               $desc = $fb_update->description;

               //Add www.facebook.com to hyperlinks
               $desc = str_replace('href="', 'href="http://www.facebook.com', $desc);   

               //Converts UTF-8 into ISO-8859-1 to solve special symbols issues
               $desc = iconv("UTF-8", "ISO-8859-1//TRANSLIT", $desc);

               //Get status update time
               $pubdate = strtotime($fb_update->pubDate);
               $propertime = gmdate('F jS Y, H:i', $pubdate);  //Customize this to your liking

               //Get link to update
               $linkback = $fb_update->link;

               //Store values in array
               $fb_item = array(
                      'desc' => $desc,
                      'date' => $propertime,
                      'link' => $linkback
               );
               array_push($fb_array, $fb_item);

               $maxnumber--;
          }          
     }
     //Return array
     return $fb_array;
}
?>

Printing out Facebook status updates

Now that you have the function available, all you need to do is to call it with the right arguments (the Facebook status updates URL which you found using the guide above must be a string – enclosed in '' or "", and the number of status updates you want to fetch must be a integer) and store its return into a PHP array. I’ve included an example of calling the above function (arguments marked with red underline), iterating through the return array and printing the values. In the example below I’ve chosen to wrap the data inside an unordered list and spans to separate the different items for styling with CSS, but you can customize the wrappings in any way you want them.

<?php
//Run the function with the url and a number as arguments
$myfb_statuses = fetch_fb_feed('http://facebook.com/feeds/status.php?id=xxxxxx&viewer=xxxxxx&key=xxxxx&format=rss20', 3);
  
//Print Facebook status updates
echo '<ul class="fb-updates">';
   foreach ($myfb_statuses as $k => $v) {
      echo '<li>';
      echo '<span class="update">' .$v['desc']. '</span>';
      echo '<span class="date">' .$v['date']. '</span>';
      echo '<span class="link"><a href="' .$v['link']. '">Link to status update</a></span>';
      echo '</li>';
   } 
echo '</ul>';
?>

I hope this was useful in some way. Please let me know if this doesn’t work for you, if you find something seriously wrong or have tips for improvement. Error handling should be implemented, such as argument checking or a timeout if Facebook is down, but I wanted to keep it as simple as possible. I’d probably extend this function some time, and keep it up to date with Facebook system changes.

Share this post:
FacebookTwitterEmailShare