Posted: 17th March 2015

Author: Ric

Tagged: Tutorials

Reading from a Facebook page with PHP

It's surprisingly easy to output a Facebook post onto your website using PHP. Use this short snippet of code to display your own Facebook page posts.

<p>&quot;<?php
    // First we need the Facebook ID of our page. You can get this from the About -> Page Info screen of any Facebook page.
    $pageID = '479406922120097';

    // Hidden behind every Facebook page is a simple RSS feed, but to get to it we have to pretend to be a web browser. We do this by faking a common user agent string. This one is Chrome on a 64bit Linux system.
    ini_set('user_agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) ');

    // Next, load the RSS feed into SimpleXML.
    $facebook_xml = simplexml_load_file('http://www.facebook.com/feeds/page.php?format=rss20&id='.$pageID);

    // For this example we're just going to output the first post, and before we output it we're going to strip out everything that proceeds a double br, because that tends to be the site preview stuff that Facebook likes to autogenerate when posting a link.
    $facebook_xml_cleaned = explode('<br/><br/>', $facebook_xml->channel->item[0]->description);
    $facebook_xml_cleaned = $facebook_xml_cleaned[0];

    echo $facebook_xml_cleaned;
?>&quot;</p>

The RSS feed contains other useful data so be sure to look over it's full content and adjust this script for your own needs.

Blog posts written by former QWeb employees are not necessarily an accurate indication of the current opinions of QWeb Ltd and the information provided in tutorials might be biased or subjective, or might become out of date.

Discuss this post

Ric
26/06/2015 11:30

As of June 23rd, Facebook’s RSS feeds have been taken offline and officially deprecated, so this method no longer works.

We’ll write an article on using the Graph API to return the same data soon.

Leave a comment

Your email address is used to notify you of new comments to this thread, and also to pull your Gravatar image. Your name, email address, and message are stored as encrypted text and you won't be added to any mailing list and your details won't be shared with any third party.