• About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
Thursday, July 3, 2025
mGrowTech
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions
No Result
View All Result
mGrowTech
No Result
View All Result
Home Al, Analytics and Automation

How to build your own Facebook Sentiment Analysis Tool

Josh by Josh
June 24, 2025
in Al, Analytics and Automation
0
How to build your own Facebook Sentiment Analysis Tool
0
SHARES
0
VIEWS
Share on FacebookShare on Twitter

READ ALSO

DeepSeek R1T2 Chimera: 200% Faster Than R1-0528 With Improved Reasoning and Compact Output

Confronting the AI/energy conundrum


  • February 3, 2014
  • Vasilis Vryniotis
  • . 7 Comments

facebook-sentiment-analysis2In this article we will discuss how you can build easily a simple Facebook Sentiment Analysis tool capable of classifying public posts (both from users and from pages) as positive, negative and neutral. We are going to use Facebook’s Graph API Search and the Datumbox API 1.0v. Similar to the Twitter Sentiment Analysis tool that we built few months back, this implementation is written in PHP nevertheless you can build very easily your own tool in the computer language of your choice.

Update: The Datumbox Machine Learning Framework is now open-source and free to download. If you want to build a Sentiment Analysis classifier without hitting the API limitations, use the com.datumbox.applications.nlp.TextClassifier class.

The complete PHP code of the tool can be found on Github.

How Facebook Sentiment Analysis works?

As we discussed in previous articles, performing Sentiment Analysis requires using advanced Machine Learning and Natural Language Processing techniques. In the previous posts we saw in detail several  Text Classifiers such as the Naive Bayes, the Softmax Regression and the Max Entropy, we discussed the importance of using Feature Selection in text classification problems and finally we saw how one can develop an implementation of the Multinomial Naive Bayes classifier in JAVA.

Performing Sentiment Analysis on Facebook does not differ significantly to what we discussed in the past. In a nutshell, we need to fetch the facebook posts and extract their content and then we tokenize them in order to extract their keyword combinations. Afterwards we perform feature selection to keep only the n-grams that are important for the classification problem and we train our classifier to identify the positive, negative and neutral posts.

The above process is significantly simplified by using the Datumbox’s Machine Learning API. All that one needs to do to perform sentiment analysis on Facebook is call the Graph API search to extract the posts of interest, extract their text and call the Datumbox Sentiment Analysis API to get their classification.

Building the Facebook Sentiment Analysis tool

In order to build the Facebook Sentiment Analysis tool you require two things: To use Facebook API in order to fetch the public posts and to evaluate the polarity of the posts based on their keywords. For the first task we will use the Facebook’s Graph API search and for the second the Datumbox API 1.0v.

We will speed the development of the tool by using 2 classes: The Facebook PHP SDK which will easily allow us to access the Graph search and the Datumbox PHP-API-Client. Once again the most complicated task in the process is creating a Facebook Application which will allow us to fetch the posts from Facebook; the Datumbox integration is a piece of cake.

Creating your own Facebook Application

facebook-sentiment-analysisUnfortunately Facebook made it mandatory to authenticate before accessing their Graph Search API. Thankfully they provide a very easy to use SDK which takes care most of the technical details of the integration. Still before using it you must create by using your Facebook Account a new Facebook application.

The process is simple. Go to Facebook Developers page (you will need to register if you have never written a Facebook Application in the past). Click on Apps on the menu and select “Create New App”.

In the popup window fill in the Display Name of your application, the Namespace, select a Category and click Create App. Once the Application is created go to the main page of your Application and select Dashboard. This is where you will get your AppID and the App Secret values. Copy those values in a safe place since we will need them later.

Next go to the Settings of your application and click “+ App Platform” on the bottom of the page. On the popup up select “Website” and then on the Site URL address put the URL of the location where you will upload your tool (Example: https://localhost/). Click “Save Changes” and you are done!

Get your Datumbox API key

To access the Datumbox API sign up for a free account and visit your API Credentials panel to get your API Key.

Developing the Facebook Sentiment Analysis class

Finally all we need to do is write a simple class that integrates the two APIs. First calls the Facebook Graph Search, authenticates, fetches the posts and then passes them to Datumbox API to retrieve their polarity.

Here is the code of the class along with the necessary comments.


<?php
include_once(dirname(__FILE__).'/DatumboxAPI.php');
include_once(dirname(__FILE__).'/facebook-php-sdk/src/facebook.php');
class FacebookSentimentAnalysis {
    
    protected $datumbox_api_key; //Your Datumbox API Key. Get it from https://www.datumbox.com/apikeys/view/
    
    protected $app_id; //Your Facebook APP Id. Get it from https://developers.facebook.com/ 
    protected $app_secret; //Your Facebook APP Id. Get it from https://developers.facebook.com/
    
    /**
    * The constructor of the class
    * 
    * @param string $datumbox_api_key   Your Datumbox API Key
    * @param string $app_id             Your Facebook App Id
    * @param string $app_secret         Your Facebook App Secret
    * 
    * @return FacebookSentimentAnalysis  
    */
    public function __construct($datumbox_api_key, $app_id, $app_secret){
        $this->datumbox_api_key=$datumbox_api_key;
        
        $this->app_id=$app_id;
        $this->app_secret=$app_secret;
    }
    
    /**
    * This function fetches the fb posts list and evaluates their sentiment
    * 
    * @param array $facebookSearchParams The Facebook Search Parameters that are passed to Facebook API. Read more here https://developers.facebook.com/docs/reference/api/search/
    * 
    * @return array
    */
    public function sentimentAnalysis($facebookSearchParams) {
        $posts=$this->getPosts($facebookSearchParams);
        
        return $this->findSentiment($posts);
    }
    
    /**
    * Calls the Open Graph Search method of the Facebook API for particular Graph API Search Parameters and returns the list of posts that match the search criteria.
    * 
    * @param mixed $facebookSearchParams The Facebook Search Parameters that are passed to Facebook API. Read more here https://developers.facebook.com/docs/reference/api/search/
    * 
    * @return array $posts
    */
    protected function getPosts($facebookSearchParams) {
        //Use the Facebook SDK Client
        $Client = new Facebook(array(
          'appId'  => $this->app_id,
          'secret' => $this->app_secret,
        ));

        // Get User ID
        $user = $Client->getUser();

        //if Use is not set, redirect to login page
        if(!$user) {
            header('Location: '.$Client->getLoginUrl());
            die();
        }
        
        $posts = $Client->api('/search', 'GET', $facebookSearchParams); //call the service and get the list of posts
        
        unset($Client);
        
        return $posts;
    }
    
    /**
    * Finds the Sentiment for a list of Facebook posts.
    * 
    * @param array $posts List of posts coming from Facebook's API
    * 
    * @param array $posts
    */
    protected function findSentiment($posts) {
        $DatumboxAPI = new DatumboxAPI($this->datumbox_api_key); //initialize the DatumboxAPI client
        
        $results=array();
        if(!isset($posts['data'])) {
            return $results;
        }
        
        foreach($posts['data'] as $post) { //foreach of the posts that we received
            $message=isset($post['message'])?$post['message']:'';
            
            if(isset($post['caption'])) {
                $message.=("\n\n".$post['caption']);
            }
            if(isset($post['description'])) {
                $message.=("\n\n".$post['description']);
            }
            if(isset($post['link'])) {
                $message.=("\n\n".$post['link']);
            }
            
            $message=trim($message);
            if($message!='') {
                $sentiment=$DatumboxAPI->SentimentAnalysis(strip_tags($message)); //call Datumbox service to get the sentiment
                
                if($sentiment!=false) { //if the sentiment is not false, the API call was successful.
                    $tmp = explode('_',$post['id']);
                    if(!isset($tmp[1])) {
                        $tmp[1]='';
                    }
                    $results[]=array( //add the post message in the results
                        'id'=>$post['id'],
                        'user'=>$post['from']['name'],
                        'text'=>$message,
                        'url'=>'https://www.facebook.com/'.$tmp[0].'/posts/'.$tmp[1],
                        'sentiment'=>$sentiment,
                    );
                }
            }
        }
        
        unset($posts);
        unset($DatumboxAPI);
        
        return $results;
    }
}


As you can see above on the constructor we pass the keys which are required to access the 2 APIs. On the public method sentimentAnalysis() we initialize the Facebook Client, we authenticate and we retrieve the list of posts. Note that if you have not yet authorized your application or if you are not logged in to Facebook with your account, you will be redirected to Facebook.com to login and authorize the app (it’s your app, no worries about privacy issues). Once the list of posts is retrieved they are passed to Datumbox API to get their polarity.

You are good to go! You are ready to use this class to perform Sentiment Analysis on Facebook. You can download the complete PHP code of the Facebook Sentiment Analysis tool from Github.

Using and Expanding the Implementation

To use the provided tool you need to create the Facebook Application as described above and then configure it by modifying the config.php file. In this file you will need to put the Datumbox API key, the Facebook App Id and Secret that you copied earlier.

Finally in the previous post we have built a standalone Twitter Sentiment Analysis tool. It will not take you more than 10 minutes to merge the 2 implementations and create a single tool which is capable of fetching posts both from Facebook and Twitter and presenting the results in a single report.

If you enjoyed the article please take a minute to share it on Facebook or Twitter! 🙂



Source_link

Related Posts

DeepSeek R1T2 Chimera: 200% Faster Than R1-0528 With Improved Reasoning and Compact Output
Al, Analytics and Automation

DeepSeek R1T2 Chimera: 200% Faster Than R1-0528 With Improved Reasoning and Compact Output

July 3, 2025
Confronting the AI/energy conundrum
Al, Analytics and Automation

Confronting the AI/energy conundrum

July 3, 2025
Baidu Open Sources ERNIE 4.5: LLM Series Scaling from 0.3B to 424B Parameters
Al, Analytics and Automation

Baidu Open Sources ERNIE 4.5: LLM Series Scaling from 0.3B to 424B Parameters

July 2, 2025
Novel method detects microbial contamination in cell cultures | MIT News
Al, Analytics and Automation

Novel method detects microbial contamination in cell cultures | MIT News

July 2, 2025
Baidu Researchers Propose AI Search Paradigm: A Multi-Agent Framework for Smarter Information Retrieval
Al, Analytics and Automation

Baidu Researchers Propose AI Search Paradigm: A Multi-Agent Framework for Smarter Information Retrieval

July 2, 2025
Merging design and computer science in creative ways | MIT News
Al, Analytics and Automation

Merging design and computer science in creative ways | MIT News

July 1, 2025
Next Post
34 Viral TikTok Gifts That Are Actually Worth a Look (2025)

34 Viral TikTok Gifts That Are Actually Worth a Look (2025)

Leave a Reply Cancel reply

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

POPULAR NEWS

Communication Effectiveness Skills For Business Leaders

Communication Effectiveness Skills For Business Leaders

June 10, 2025
7 Best EOR Platforms for Software Companies in 2025

7 Best EOR Platforms for Software Companies in 2025

June 21, 2025
Eating Bugs – MetaDevo

Eating Bugs – MetaDevo

May 29, 2025
Top B2B & Marketing Podcasts to Lead You to Succeed in 2025 – TopRank® Marketing

Top B2B & Marketing Podcasts to Lead You to Succeed in 2025 – TopRank® Marketing

May 30, 2025
Entries For The Elektra Awards 2025 Are Now Open!

Entries For The Elektra Awards 2025 Are Now Open!

May 30, 2025

EDITOR'S PICK

Cloud quantum computing: A trillion-dollar opportunity with dangerous hidden risks

Cloud quantum computing: A trillion-dollar opportunity with dangerous hidden risks

June 21, 2025
Moburst Named Top Mobile Marketing Agency by MobileAppDaily

Moburst Named Top Mobile Marketing Agency by MobileAppDaily

June 29, 2025
Trade Show Industry Updates: News, Data, Trends

Trade Show Industry Updates: News, Data, Trends

June 18, 2025

Japan probe finds more universities discriminated against women

March 17, 2025

About

We bring you the best Premium WordPress Themes that perfect for news, magazine, personal blog, etc. Check our landing page for details.

Follow us

Categories

  • Account Based Marketing
  • Ad Management
  • Al, Analytics and Automation
  • Brand Management
  • Channel Marketing
  • Digital Marketing
  • Direct Marketing
  • Event Management
  • Google Marketing
  • Marketing Attribution and Consulting
  • Marketing Automation
  • Mobile Marketing
  • PR Solutions
  • Social Media Management
  • Technology And Software
  • Uncategorized

Recent Posts

  • Squid Game X Script (No Key, Auto Win, Glass Marker)
  • DeepSeek R1T2 Chimera: 200% Faster Than R1-0528 With Improved Reasoning and Compact Output
  • Google’s customizable Gemini chatbots are now in Docs, Sheets, and Gmail
  • 24 Effective Ways to Drive Website Traffic in 2025 (Complete Guide)
  • About Us
  • Disclaimer
  • Contact Us
  • Privacy Policy
No Result
View All Result
  • Technology And Software
    • Account Based Marketing
    • Channel Marketing
    • Marketing Automation
      • Al, Analytics and Automation
      • Ad Management
  • Digital Marketing
    • Social Media Management
    • Google Marketing
  • Direct Marketing
    • Brand Management
    • Marketing Attribution and Consulting
  • Mobile Marketing
  • Event Management
  • PR Solutions

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?