Facebook Page feed on website-PHP

Following is the code to display your facebook page feed on your website using PHP, cURL :

It would display top 5 posts on your Facebook page as the limit which I gave here 5.

All you would need is your PAGE-ID, APP-ID, APP-SECRET

$page_name = yourpage_name; // Example: http://facebook.com/{PAGE_NAME}
$page_id = yourpageid; // can get form Facebook page settings
$app_id = yourfacebookappid; // can get form Developer Facebook Page
$app_secret = yourfacebooksecret; // can get form Developer Facebook Page
$access_token = "https://graph.facebook.com/oauth/access_token?client_id=$app_id&client_secret=$app_secret&grant_type=client_credentials";
//@$access_token = file_get_contents($access_token); // returns 'accesstoken=APP_TOKEN|APP_SECRET'
$curlSession = curl_init();
curl_setopt( $curlSession, CURLOPT_URL, $access_token );
curl_setopt( $curlSession, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $curlSession, CURLOPT_RETURNTRANSFER, true );
$access_token = curl_exec( $curlSession );
curl_close( $curlSession );

//echo $access_token;
$access_token = json_decode( $access_token, true );
$access_token = $access_token[ 'access_token' ];
$limit = 5;

$curlSession = curl_init();
curl_setopt( $curlSession, CURLOPT_URL, "https://graph.facebook.com/v3.0/$page_name/posts?fields=picture,message,id&limit=$limit&access_token=$access_token" );
curl_setopt( $curlSession, CURLOPT_BINARYTRANSFER, true );
curl_setopt( $curlSession, CURLOPT_RETURNTRANSFER, true );
$data = curl_exec( $curlSession );
curl_close( $curlSession );
//echo $data;

$data = json_decode( $data, true );
$posts = $data[ "data" ];
//echo sizeof($posts);

for ( $i = 0; $i < sizeof( $posts ); $i++ ) {
 //echo $posts[$i][id];
 $link_id = str_replace( $page_id . "_", '', $posts[ $i ][ "id" ] );
 if ( isset( $posts[ $i ][ "message" ] ) ) {
 $message = htmlspecialchars_decode( $posts[ $i ][ "message" ] );
 $message = utf8_decode( $message );
 } else {
 $message = '';
 }
 $picture = htmlspecialchars_decode( !empty( $posts[ $i ][ "picture" ] ) ? $posts[ $i ][ "picture" ] : "" );

 $message = str_replace( '?', "'", utf8_decode( $message ) );
 echo $fb_feed = "<a target='_blank' href='https://www.facebook.com/yourpagename/posts/" . $link_id . "'>" . $message . "<br><img src=" . $picture . " align='center'></a>";
}

Leave a Reply