August 6, 2014 8:22 pm

Search Content in Facebook with Open Graph API in PHP

In this tutorial I will show you that how to search on Facebook using open graph API in PHP. Using Open Graph search you can access all public data very easily by typing your required word like “PHP” you will get all the information shared publicly on facebook contain word PHP. Its very simple and easy to integrate and you can access your required data on a single page.

Search Content in Facebook with Open Graph API in PHP

[wpdm_file id=108]DEMO

To implement this search you need to create an facebook application we have already explained how to create a Facebook application in our previous tutorial so we are not repeating same procedure again.

We need a oauth token to run open graph query so you need to authenticate first so we can get your access token from facebook and after that you can see a form where you put your keyword and search type like Post, Group, Page, Event or Place ie: you search Delhi in places it will show all places in Delhi.

Index.php

Contains PHP code for facebook authentication and display lists.

<?php
session_start();  
require 'fbSearcher.php';
require 'src/config.php';
require 'src/facebook.php';

// Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
  'appId'  => $config['App_ID'],
  'secret' => $config['App_Secret'],
  'cookie' => true
)); 
$vars = $_POST; 

if(isset($_GET['fbTrue']))
{
    $token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=".$config['App_ID']."&redirect_uri=" . urlencode($config['callback_url'])
       . "&client_secret=".$config['App_Secret']."&code=" . $_GET['code']; 

     $response = file_get_contents_curl($token_url);

     $params = null;
     parse_str($response, $params);
     $_SESSION['token'] = $params['access_token'];
     $content = '<form action="index.php" method="post"> 
        <input type="text" name="q" value="'.$vars['q'].'"></input> 
        <select name="type"> 
            <option value="post">Post</option> 
            <option value="event">Event</option> 
            <option value="place">Place</option> 
            <option value="page">Page</option> 
            <option value="group">Group</option>  
        </select><input type="submit" value="search"></input></form>';
} 
elseif(isset($_POST['q']))
{
    if($_POST['q'] != "")
    {
        $searcher = new facebookSearcher(); 
        $searcher->setQuery($vars['q']) 
                ->setType($vars['type']) 
                ->setAccessToken($_SESSION['token']) 
                ->setLimit(30); 
        $graph_res = $searcher->fetchResults(); 
        if(count($graph_res->data) == 0)  exit("No Results"); 
        if($vars['type'] == 'post')
        {
            //post 
            foreach($graph_res->data as $post)
            {
                $row[] = "<img src='{$post->icon}' />".$post->type; 
                $row[] = $post->from->name; 
                $row[] = $post->message; 
                $row[] = "<a href='{$post->link}' target='_blank'>{$post->link}</a>"; 
                $row[] = $post->likes->count." Likes"; 
                $table[] = $row; 
                unset($row);
            }
        }
        elseif($vars['type'] == 'event')
        {
            foreach($graph_res->data as $post)
            {
                $row[] = $post->name; 
                $row[] = "At ".$post->location; 
                $row[] = "From ".$post->start_time." To ".$post->end_time; 
                $row[] = "<a href='https://www.facebook.com/events/{$post->id}' target='_blank'>View</a>"; 
                $table[] = $row; 
                unset($row);
            }
        }
        elseif($vars['type'] == 'place')
        {
            foreach($graph_res->data as $post)
            {
                $row[] = $post->name; 
                $row[] = $post->category; 
                $row[] = $post->location->street.", ".$post->location->city.", ".$post->location->country;
                $row[] = "<a href='https://www.facebook.com/{$post->id}' target='_blank'>View</a>";  
                $table[] = $row; 
                unset($row);
            }
        }
        elseif($vars['type'] == 'page')
        {
            foreach($graph_res->data as $post)
            {
                $row[] = $post->name; 
                $row[] = $post->category; 
                $row[] = "<a href='https://www.facebook.com/{$post->id}' target='_blank'>View</a>"; 
                $table[] = $row; 
                unset($row);
            }
        }
        elseif($vars['type'] == 'group')
        {
            foreach($graph_res->data as $post)
            {
                $row[] = $post->name; 
                $row[] = "<a href='https://www.facebook.com/{$post->id}' target='_blank'>View</a>"; 
                $table[] = $row; 
                unset($row);
            }
        }
        else
        {     
            $content .= "<h2>Nothing Found.</h2>";
        }
        $content = '<form action="index.php" method="post"> 
            <input type="text" name="q" value="'.$vars['q'].'"></input> 
            <select name="type"> 
                <option value="post">Post</option> 
                <option value="event">Event</option> 
                <option value="place">Place</option> 
                <option value="page">Page</option> 
                <option value="group">Group</option>  
            </select><input type="submit" value="search"></input></form>';        
        $content .= "<table width='800' border='1'> ";

        foreach ($table as $row){ 
            $content .= "<tr>"; 
            foreach ($row as $cell){ 
                $content .= "<td>{$cell}</td>"; 
            } 
            $content .= "</tr>"; 
        } 
        $content .= "</table> ";
    }
    else
    {
         $content .= "<h2>Search {$vars['type']}s For : {$vars['q']}</h2>";
         $content .= "<h2>Nothing Found.</h2>";
         
    }
}
else
{
     $content = '<a href="https://www.facebook.com/dialog/oauth?client_id='.$config['App_ID'].'&redirect_uri='.$config['callback_url'].'"><img src="./images/login-button.png" alt="Sign in with Facebook"/></a>';
     
}

echo $content;

?>

Above code used to get your access token and store it in session, after that show you a form to search anything on facebook public postings. Used a class fbSearcher.php contains some functions like call Graph query url and return data to the main page you can get this class and other required files in our download script freely available.

A live demo and complete code available for download for free download code and enjoy.

[wpdm_file id=108]DEMO

I hope you like this tutorial an please don’t forget to comment below your views and suggestion for improvement.

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:

7 responses to “Search Content in Facebook with Open Graph API in PHP”

  1. Mawia HL says:

    I tested the code, but all I could get is no result even if I type the existing fan page in the input select provided in the demo. What could be wrong? Any way I really like the idea especially for implementing in site. Go on…

  2. expy movies says:

    I Agree with Mawia HL . we are trying to access but no result found as yet. and most unfortunate part is there is no support.

  3. Irma Gerd says:

    Regarding the previous comments: Facebook disabled the graph search for all app keys created after 2013.

  4. Anh Khoa Truong says:

    I like this tut. Thank’s

  5. Anh Khoa Truong says:

    My Demo :

    Notice: Undefined index: access_token in C:xampphtdocsprojectindex.php on line 25

    Notice: Undefined index: q in C:xampphtdocsprojectindex.php on line 27

    Please tell me why ??? Thank’s.

  6. Andrej Vl says:

    Hi ,
    I have the same problem as Anh Khoa Truong :

    Notice: Undefined index: access_token in C:wampwwwsearchindex.php on line 25

    Notice: Undefined index: q in C:wampwwwsearchindex.php on line 27

    But can’t see answer. Please help my .

Leave a Reply

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