Using the Facebook Graph API, PHP and MySQL: How to Collect and Store Public Data in 5 Steps

using PHP and the Graph API.

How to use the Facebook Graph API and PHP to gather public data

This article is for new developers who aren’t sure how to automatically (or “programmatically”) integrate the Graph API into a Facebook application. Code samples are provided at the end of this article. Feel free to copy them now and come back later if you are having troubles with implementation. This tutorial assumes you have created a Facebook developers account and registered an app. If you have not you will need to complete those steps first.

Assumptions

  1. Facebook Developers Account and registered application
  2. MySQL database
  3. Local development environment
  4. Text editor

Steps

  1. Define your search query
  2. Define a trigger event
  3. Call the API
  4. Collect the Results
  5. Store the Results

Introduction to the Facebook Graph API

The Facebook Graph API is a wonderful tool for adding dynamic data to your application. How you do that programmatically can get a bit tricky. You are probably familiar with the Graph API Explorer. This is a great place to test different search queries since those results are immediately available. But you don’t want to have to visit the Graph API Explorer page every time you need new data. You’d have to constantly enter a new search query, copy the results, paste them into a new file, and upload them to your database to deliver meaningful results to your end users. So how do you get all that beautiful data into your app automatically?

Below, I’ll show you how to “Set It and Forget It.” This approach ensures that your users are receiving accurate and relevant information each time when they use your app. How you choose to display your data in entirely up to you. Once you have control over when to collect the data and where to store it, your options are limited only by your imagination…

5 steps for collecting public Facebook Data

Step 1: Define Your Search Query

The Facebook Graph API collects information stored in a specific location, or an “endpoint”. It’s up to you to explore those endpoints and determine which ones contain the information relevant to your application. In this example we’re pulling restaurant data from Delray Beach, FL. It results in a URL (universal resource locator) that looks like this:

'https://graph.facebook.com/v2.4/search?q=restaurant&
type=place&distance=3200¢er=center=26.47,-80.07&
fields=location,name,likes,talking_about_count,were_here_count,description,website,cover,about,culinary_team&
limit=250&access_token=5893781074754054|r-KJ2eJLHOHLHlhf-eohdOH-LHd'


The URL contains all of our search parameters.

  1. search?q=restaurant
  2. &type=place
  3. &distance=3200
  4. ¢er=26.47,-80.07
  5. &fields=location,name,likes,talking_about_count,were_here_count,description,website,cover,about,culinary_team
  6. &limit=50
  7. &access_token=5893781074754054|r-KJ2eJLHOHLHlhf-eohdOH-LHd

The first two parameters in the list above search endpoints for “restaurants” that are of the “place” type. Items 3 and 4 establish where we are looking for restaurants. In this case we are looking within a 3,200 meter radius from the center of Delray Beach, located at 26.47 degrees latitude, -80.07 degrees longitude. Item 5 lists all the fields we want to collect information from. These will vary depending on your needs. Here is where we recommend using the Facebook Graph API Explorer since it has built-in features that help you find these endpoints. Item 6 simply caps the number of results that will be returned. Item 7 is your app access token. This token is only available to you once you have registered as a Facebook developer and have created an application. If you are using this code straight from the page (you can download the source code at the end of this post) be sure to substitute your own access token.

Step 2: Define a trigger event

A trigger event is your “start button”. The trigger event will be unique to your app but in this case it is simply loading inside your browser window the page where the ‘fb_collect.php‘ file lives. At Circle Squared Publishing we use MAMP to create our local development environment. The “local” directory folder serves as our root directory or “web root”.

The trigger event is initiated when the browser opens the file named ‘fb_collect.php.’ The way you tell it to open that file is by entering in the specific URL into your web browser search bar. For the directory structure shown here, that URL is http://localhost/blog/fb_collect.php.

All of your directories and files within those directories are accessible by a web browser. When you migrate your code from the local environment inside your computer into a production environment located inside a remote web server (and available to the public) it’s in your best interest to store sensitive information, such as database connection credentials, outside of the web root. This ensures that no one can access that information through their web browser.  In the code samples below you will see a line that looks like this: require('/Users/admin/Documents/credentials/connect_tutorials.php';) This is outside of the web root and is where we store the credentials for logging into our database.

Step 3: Make the Call to the Facebook Graph API

To “make the call” (send a request) to the Facebook Graph API using the URL defined above, we first want to create a file with the same base name as the execution script. In this example, the execution script is called ‘fb_collect.php‘. This practice helps to keep our API calls and the results from those calls in sync. We achieve this programmatically by creating a variable named $table and setting it equal to the base name of the current file minus the .php extension.

Next we create another variable called $name and set it equal to the variable $table. Then we append the extension .json since that is the format in which we’ll retrieve our results.

The last step is to create a third variable, called $fp in this example, and set it equal to the PHP fopen() function passing it the $name variable and making the file it opens writeable by passing in the ‘w‘ parameter.

https://gist.github.com/CircleSquaredPublishing/8dd521b838f09bcfb291

Now we’ve created a new file, ‘fb_collect.json‘, opened that file, and made it writeable. Here is where we actually make the call using the PHP cURL library of functions. cURL is a popular and robust way to transfer and receive data using URL syntax. Click here to peruse the cURL Manual.

https://gist.github.com/CircleSquaredPublishing/d27db4894c414d238512

Step 4: Collect the Results

To collect the results of our query, we need to create a table in our database. Here is the “create table” syntax we used. What you cannot see here is the database trigger we use to add the current date to the fb_date column each time we insert data into the database.

Back in our fb_collect.php file, we create a variable named $results and set it equal to the PHP function file_get_contents() passing in the $name variable.  In the steps above, we wrote the results into the $name variable, which is an actual file that we created named ‘fb_collect.json‘.

https://gist.github.com/CircleSquaredPublishing/69bf2e4321002c6ab21a

Line 5 above is a personal preference and simply prints the contents of the $results variable into the browser window. This lets you know that the call has been successful and you have received data. The results will look something like this in the browser and like this in the ‘fb_collect.json‘ file if opened in a text editor.

At Circle Squared Publishing, Atom is our text editor of choice. One great reason to use a text editor like Atom is the ability to turn a jumbled mess  into an easy-to-read, associative array by using the beautify feature.

Step 5: Store the Results

This is where the bulk of the code is written. Each block of this section is worthy of its own tutorial, so for now we will keep it simple and show you a method that works using prepared statements and a foreach loop.

https://gist.github.com/CircleSquaredPublishing/da75d590d39224bb0c26

Once you execute ‘fb_collect.php‘, your database table should now be populated with data. It should look something like this:

Here is the complete script:

https://gist.github.com/CircleSquaredPublishing/7666814e86fbe16eb27b

How you decide to analyze and display the data is up to you…


William Conkwright

Will Conkwright is the owner at Circle Squared Publishing, LLC, a photographer, writer, full stack web developer, Google Street View Trusted Photographer, competitive cyclist, endurance athlete and adventure junky who loves riding motorcycles.

Subscribe for premium content

Subscribers receive members only content delivered straight to their inbox. Admission is free. Inspiration is priceless.

Related Articles

Tutorials

Dinghy valves and the caps that accompany them

Captain Zoey Zaleta of Offshore Rafting So you think... Read More

Mental Health | Writing

You’re The Problem

But I Have a Solution “…school shootings are more... Read More

Email Confessions | Photography | Writing

Peer Acceptance

The joys of peer acceptance Dear Respected Photographer, The... Read More