June 30, 2016 1:31 am

An introduction to Facebook’s PHP SDK- Creating a Sentiment Analysis app

We will be building a simple app which takes from the user the id/name of a Facebook page (the name written in the URL when visiting a Facebook page) and shows some statistics related to the sentiment of the last 100 posts of that Facebook page. It shows whether the page is positive, negative or neutral, how many of the last one hundred posts are considered positive, negative or neutral and it pinpoint the total distribution of positivity, negativity and neutrality in those posts.

An introduction to Facebook’s PHP SDK- Creating a Sentiment Analysis app

Facebook post extraction (Analysis.php)

We start by importing the Facebook PHP SDK (more information on it could be found at:

https://developers.facebook.com/docs/reference/php/) and phpInsight which is a PHP library that carries out sentiment analysis (it can be found at: https://github.com/Sysfotech/phpInsight). Then, we create a Facebook app with our desired profile and set the Facebook app’s id and the app’s secret key in constants.

Then,we proceed with creating our analysis class.

Whenever the class is instantiated, we set the name of the page in a class property, try to get its posts and the sentiment of those posts, if there was no error fetching the posts.

To get the posts of the page, we would have to get ourselves an app token. We do not need a user access token to get the public posts of an arbitrary page on Facebook, so all we need is to have an app and know its secret key and its id and make a request to get the necessary token. We have already imported the Facebook SDK, so we istantiate  the Facebook class, pass it our app id and secret key and save the results in the fb property of our own class. Then, we make a request to Facebook’s /oauth/access_token endpoint using the SDK’s get method passing it our app id and app secret and get the token from the response.

As we now have an app access token, we can get the last 100 public posts of any page. Therefore, we use the get method once again to query the desired page for its 100 posts ( we can take less if we want by changing the number 100 in the limit GET parameter)  and pass the access token in the URL parameters.  If something goes wrong, we set a generic error and if no posts are returned to us we set up another error to show to the user.

There it is, now we can collect the posts of any Facebook page and analyze or mine their content in any way our app needs.

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories: