May 19, 2016 5:47 am

How to get Facebook Page Feed with graph API using PHP & MySQL

In this tutorial I will show you that how to get Facebook pages public feed using graph API without any authentication. You can run this script on console, on local host or you can run this script on your live website. This tutorial get a Facebook page URL and Facebook application id and secret that’s it.

How to get Facebook Page Feed with graph API using PHP & MySQL

[wpdm_file id=172]DEMO

Let’s start from app creation.

Step 1: create Facebook application click here

step 1 Facebook for Developers

Step 2: Chose platform where to use application select website.

Step 2 Facebook for Developers

Step 3: Write your application name and click Create New Facebook App ID button.

step 3 Facebook for Developers

Step 4: Select settings for application and give your email.

step 4 Facebook for Developers

Step 5: Skip quick start

step 5 Facebook for Developers

Step 6: App setup from sandbox to live on review page

step 6 App Review Facebook for Developers

Final Step for application creation and setting: Copy application ID and Secret from settings page

step 7 phpgang feed app Dashboard Facebook for Developers

Read Also: How to Login with Facebook API SDK v5 in PHP

Now Coding for your feed application

Feed_database.sql

Import tables in your database.

-- phpMyAdmin SQL Dump
-- version 2.8.0.1
-- http://www.phpmyadmin.net
-- 
-- Host: custsql-pow22
-- Generation Time: May 16, 2016 at 05:16 AM
-- Server version: 5.5.46
-- PHP Version: 4.4.9
-- 
-- Database: `database`
-- 

-- --------------------------------------------------------

-- 
-- Table structure for table `feed`
-- 

CREATE TABLE `feed` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `PageID` varchar(100) NOT NULL,
  `Date` datetime NOT NULL,
  `Post` text NOT NULL,
  `Picture` text NOT NULL,
  `Comments` varchar(10) NOT NULL,
  `Likes` varchar(10) NOT NULL,
  `Shares` varchar(10) NOT NULL,
  `PostID` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `PostID` (`PostID`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- 
-- Dumping data for table `feed`
-- 


-- --------------------------------------------------------

-- 
-- Table structure for table `pages`
-- 

CREATE TABLE `pages` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `PageID` varchar(100) NOT NULL,
  `Name` varchar(255) NOT NULL,
  `Likes` varchar(100) NOT NULL,
  `Talking` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

-- 
-- Dumping data for table `pages`
--

db.php

Configure your database connection file.

<?php

$connection = mysqli_connect('localhost','DBUser','DBPassword','DBName') or die(mysqli_error($connection));
?>

config.php

Application configuration file, modify CALL BACK URLYour App ID and Your App Secret values.

<?php

//Facebook configuration
$config['App_ID']      =   'YOUR_FACEBOOK_APPLICATION_ID';
$config['App_Secret']  =   'YOUR_FACEBOOK_APPLICATION_SECRET'; 

?>

index.php

Index file used to show you a form where you need to add your application unique name or id.

Page Name or page id

<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Facebook Pages Feed</title>
</head>
<body>
<form method='post' action='feed.php'>Enter Page unique id / unique name here: <input type='text' name='page' value="" /><input type=submit /></form>
</body>
</html>

feed.php

This is the main file used to get page info and feeds and store in database.

<?php
if(isset($_REQUEST['page']))
{
 require_once('db.php'); // Database connection
 require_once( 'config.php' ); // Configuration file contain facebook application id and secret
 $token = $config['App_ID']."|".$config['App_Secret']; // making app token by its id and secret
 
 $pageDetails = getFacebookId(mysqli_real_escape_string($connection,$_REQUEST['page'])); // Get page details like name of page, page ID, Likes, people talking about that page.
 if(!isset($pageDetails->id))
 {
 echo "Error Occured please provide a valid facebook page unique id / unique name";
 exit;
 }
 $query = "SELECT * FROM pages where PageID='".$pageDetails->id."'"; // select page already in database or not query.
 $result = mysqli_query($connection,$query); // execute query
 $numResults = mysqli_num_rows($result); // number of records
 if($numResults>=1) // if page found in database then run update query
 {
 $Results = mysqli_fetch_array($result);
 mysqli_query($connection,"UPDATE `pages` SET `Name` = '".mysqli_real_escape_string($connection,$pageDetails->name)."',`Likes` = '".$pageDetails->fan_count."',`Talking` = '".$pageDetails->talking_about_count."' 
 WHERE `id` ='".$Results['id']."' LIMIT 1");
 }
 else // else run insert query for new page
 {
 mysqli_query($connection,"INSERT INTO `pages` ( `id` , `PageID` , `Name` , `Likes` , `Talking` )
 VALUES 
 (NULL , '".$pageDetails->id."', '".$pageDetails->name."', '".$pageDetails->fan_count."', '".$pageDetails->talking_about_count."')");
 }

 feedExtract("",$pageDetails->id,$token); // This function will get feed of page.
 header("Location: view.php");
 exit;
}
else
{
 header("Location: index.php");
 exit;
}
 
// Function to get all feed of a page with like, comment and share count.
function feedExtract($url="",$pageFBID) // $url contain url for next pages and $page contain page id
{
 global $token, $connection; // database connection and tocken required
 
 // first time fetch page posts
 $response = file_get_contents_curl("https://graph.facebook.com/v2.6/$pageFBID/feed?fields=picture,message,story,created_time,shares,likes.limit(1).summary(true),comments.limit(1).summary(true)&access_token=".$token);
 
 $query = "SELECT id FROM pages where pageID='".$pageFBID."'"; // select feed already in database or not query.
 $result = mysqli_query($connection,$query); // execute query
 $fieldID = mysqli_fetch_row($result);
 $pageID = $fieldID['0'];
 // decode json data to array
 $get_data = json_decode($response,true);
 // loop extract data
 for($ic=0;$ic<count($get_data['data']);$ic++)
 {
 // Exracting Day, Month, Year
 $date = date_create($get_data['data'][$ic]['created_time']);
 $newDate = date_format($date,'Y-m-d H:i:s');
 
 
 // $story of post in if link, video or image it will return "message" plain status as "story"
 $story = $get_data['data'][$ic]['message'];
 
 if(!isset($story))
 $story = $get_data['data'][$ic]['story'];
 
 
 $query = "SELECT id FROM feed where PostID='".$get_data['data'][$ic]['id']."'"; // select page id from pages table.
 $result = mysqli_query($connection,$query); // execute query
 $numResults = mysqli_num_rows($result); // number of records
 if($numResults>=1) // if post found in database then run update query
 {
 //Update Record
 mysqli_query($connection,"update `feed` set 
 `Comments` = '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['comments']['summary']['total_count'])."' , 
 `Likes` = '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['likes']['summary']['total_count'])."', 
 `Shares` = '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['shares']['count'])."' 
 where `PostID` = '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['id'])."'");
 }
 else
 {
 
 // Puting data in sql query values
 $dataFeed = "(
 '".mysqli_real_escape_string($connection,$pageID)."', 
 '".mysqli_real_escape_string($connection,$newDate)."',
 '".mysqli_real_escape_string($connection,$story)."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['picture'])."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['comments']['summary']['total_count'])."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['likes']['summary']['total_count'])."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['shares']['count'])."',
 '".mysqli_real_escape_string($connection,$get_data['data'][$ic]['id'])."')";
 
 mysqli_query($connection,"INSERT INTO `feed` (`PageID` , `Date` , `Post` , `Picture` , `Comments` , `Likes` , `Shares` , `PostID` ) VALUES $dataFeed");
 }
 }
 
 // Return message.
 return 1;
}

function getFacebookId($pageID) // This function return facebook page details by its url
{
 // get token from main file
 global $token; 
 $json = file_get_contents_curl('https://graph.facebook.com/'.$pageID.'?fields=fan_count,talking_about_count,name&access_token='.$token); 
 // decode returned json data in arrau.
 $json = json_decode($json);
 return $json;
}

?>

This file will get latest 25 posts of your given page and store in database and display them on view.php file attached in download source code.

[wpdm_file id=172]DEMO

Note: If you want to get feed comments+comments reply code please contact us.

Thanks for reading my tutorial please write down your feedback in comments to improve PHPGang.

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

15 responses to “How to get Facebook Page Feed with graph API using PHP & MySQL”

  1. Nguyen Cuong says:

    Hi i get error: undefined function file_get_contents_curl()
    pls help

  2. Santhosh Kumar says:

    can you help me it is not working

  3. Santhosh Kumar says:

    my skype id is santhosh.kumar.hegde

  4. Santhosh Kumar says:

    It is working now
    how to get page details
    page name and fan count from this code

  5. Mick says:

    Thanks for this! Again a great tutorial. Grtz from The Netherlands!

  6. Arno says:

    Why the database? Can’t you just retrieve the data and publish it?

  7. shahid khan says:

    it doest allow me to download due to subscription i cant subcribe it
    could any one know how to download it?

  8. shahid khan says:

    its taking to much time to subscribe…
    is their any other way to download this
    hello any one ?

  9. alykhan says:

    Subscribe button is broken

  10. Salam Huzoor Bux!

    it’a a great piece of code but unfortunately it’s not working anymore, is there any update regarding this code?

    I would like to see it working again as I’m working on a project to retrieve all comments from a Facebook page on a php webpage, so it would be handy for me if you help me regarding this.

    Thank you,

    Regards

  11. Fábio Neves De Campos says:

    Congratulations and how we managed to get the fanpage check in, thank you

Leave a Reply

Your email address will not be published. Required fields are marked *