Twitter is one of the leading Social Networks on the internet today, used by celebrities, developers, bloggers and even Lord Voldemort! Twitter was founded in 2006 and has gone from a small startup to a multi-billion dollar company with over 230 million active users!!

Before I get started, grab yourself a brew… Put your favourite slippers on and put your feet up – this is a particularly long blog post! :)

A lot of Twitter’s success has come from the external API that allows us web folk to put the Social Network’s massive user base at our fingertips. By using the API we have access to a whole bunch of Twitter features, such as the ability to retrieve specific Tweets, as we did with our latest project for Beefeater Grill, #AnyExcuse, or even post Tweets.

Before I dive in to the technical elements of this blog post, lets first look at some statistics (developers love statistics!).

  • On average, 58,000,000 Tweets are posted every day.
  • There have been more than 300 billion Tweets posted since the Social Network was founded. To put this into perspective, the earth has a total population of roughly 7.046 billion people, that is roughly 42 Tweets to every human on earth…crazy huh?
  • The country with the largest active Twitter user base is China, with 35.5 million active users.
  • Over 3 million websites integrate with Twitter….and we’re going to add to that with this tutorial!

Enough stats and figures, lets jump in to how you can use Twitter in your application. In this quick guide I’m going to show you how we were able to retrieve Tweets for the #AnyExcuse microsite.

With the Beefeater project, it wasn’t as simple as pulling in every single Tweet that had the hashtag #AnyExcuse…can you imagine how much abuse the system would have received if we’d allowed that? We decided that, as we’d be retweeting the best ones anyway, the simplest way to administrate which ones are pulled through to the site would be to filter out the same ones we are retweeting through the @beefeatergrill account. That made it a simple way to pull through the funny excuses, and ignore any abusive/offensive ones without adding extra administration.

This guide assumes you have a local installation of Apache, MySQL & PHP setup on your computer (I personally use XAMPP for local development) or access to a LAMP environment.

We are going to use the open source tmhOAuth library, provided by themattharris on Github. Head on over to the tmhOAuth Github page and either download the repository as a zip, or alternatively clone the repo to your local machine.

Lets create a basic folder structure for your application, this will allow us to separate our libraries from our vendors.

This is how my folder structure currently looks:

- libs
- vendors
index.php

Vendors is where we store third party resources, such as the tmhOAuth library and libs is where we will be creating our classes. Index.php as you will know is where we will be pulling it all together..

So lets start by creating a new directory in vendors named “twitter”

- vendors
- twitter

Inside the twitter directory, we need to take both the tmhOAuth.php file and the cacert.perm file from the Twitter repo you retrieved above and copy them in to the directory.

In the libs directory, we need to create a file called “twitter.php” and in the root directory our main file “index.php”. Your directory should now look like this:

- libs
- twitter.php
- vendors
- twitter
- tmhOAuth.php
- cacert.perm
index.php

Time to get geeky! Lets start by creating your Twitter class. Open the libs/twitter.php file in your favourite editor (e.g. Sublime Text 2).

At the very top of your file, we want to pull in the tmhOAuth.php vendor, to do that we use the require_once(); function:

<?php
    require_once('vendors/twitter/tmhOAuth.php');
?>

This will give your entire Twitter class access to the child functions of the tmhOAuth class, now we need to open up our class:

<?php
    require_once('vendors/twitter/tmhOAuth.php');
    class Twitter{
    }
?>

Before we go any further, you need to create a Twitter application on your Twitter account to give your application access to the API. To do this head over to the Twitter developers site http://dev.twitter.com/ and sign in. Once you have logged in, hover over your avatar at the top right and choose “My applications” then click “Create a new application”. You will be presented with the “Create an application form”, fill the form in with your details, for example:

Name: Engage Twitter Dev
Description: Engage Twitter tutorial application.
Website: http://www.engageinteractive.co.uk/

Under “Developer Rules Of The Road” have a read through the conditions, once you are happy tick “Yes, I agree”.

Enter the lovely captcha field at the bottom of the page and click “Create your Twitter application”! You should now be presented with your applications developer page, this page has several tokens and keys used for giving your application access to the Twitter API. At the very bottom of the page there is a button under “Your access token” with the title “Create my access token” – click the button to generate the additional required tokens.

This sometimes takes a couple of seconds to generate, try refreshing the page after a few seconds and you should now see Access token, Access token secret and Access level.

Back to your editor, re-open the libs/twitter.php file where we will set some private variables that contain your access token details.

<?php
    require_once('vendors/twitter/tmhOAuth.php');

    class Twitter{
        private $consumer_key = "";
        private $consumer_secret = "";
        private $access_token = "";
        private $access_token_secret = "";
    }
?>

At this point you need to give the variables above the information required from your Twitter Application page that we just created.

We now need to create our __construct function.

The __construct function is the function that is run when your class is initialised, in here we need to call access to the Twitter API. To do that we need to do 2 things, the first is to create an array with your Twitter access token details then set a global variable that gives the rest of the class access to the tmhOAuth vendor.

The config array is passed to the tmhOAuth class to create a connection to the API, this uses the details stored in your private variables above.

We then create a global variable which is accessible by $this->twitter which will allow us to grab details from the tmhOAuth class.

<?php
    require_once('vendors/twitter/tmhOAuth.php');

    class Twitter{
        private $consumer_key = "";
        private $consumer_secret = "";
        private $access_token = "";
        private $access_token_secret = "";

        public function __construct(){  
            $twitter_config = array(
                'consumer_key' => $this->consumer_key,
                'consumer_secret' => $this->consumer_secret,
                'user_token' => $this->access_token,
                'user_secret' => $this->user_secret
            );

            $this->twitter = new tmhOAuth($twitter_config);
        }
    }
?>

Congratulations if you have got this far! We now have the awesome task of retrieving Tweets from the API. In this example, I’m going to show you how we filtered retweeted Tweets for a specific hashtag – most of the examples below are common PHP methods that we use to filter retrieved information.

Lets create a new function to sit under our __construct function called getTweets()!

public function getTweets(){

}

Inside this function, we need to make a request against the REST api for specific Tweets:

public function getTweets(){
    $request = $this->twitter->request(
        'GET',
        $this->twitter->url('1.1/statuses/user_timeline'),
        array(
            'exclude_replies' => true,
            'include_rts' => true,
            'count' => 50
        )
    );
}

As you can see above, we are retrieving the JSON data from the user timeline, excluding any Tweets that are replies and including retweets. This returns a JSON array that we can then manipulate. We now need to decode the response in to a PHP array.

public function getTweets(){
    $request = $this->twitter->request(
        'GET',
        $this->twitter->url('1.1/statuses/user_timeline'),
        array(
            'exclude_replies' => true,
            'include_rts' => true,
            'count' => 50
        )
    );

    $tweets = json_decode($this->twitter->response['response'], true);

    return $this->filterTweets($tweets);
}

First we decode the JSON response in to an array, then we return the Tweets passed through the filter function we are about to create.

Once we have got an array of Tweets, we can filter through them with another function and return only the ones we want to see. This is where the standard PHP methods come in to play.

Lets create a second function called filterTweets(); with an array parameter called Tweets.

public function filterTweets($tweets = array()){

}

This function will have a sole purpose of filtering the Tweets returned for any that have been retweeted, and have a specific hashtag.

Twitter appends all retweeted Tweets with “RT “ – we used these 3 characters as a method of identifying whether the Tweet was retweeted. You could also check whether the ‘retweeted_status’ key exists, this key contains information about the retweeted Tweet or as in our case, you can use both.. I apologise for the over-use of the word Tweet!

So now, we need to create an empty array called $formatted_tweets and begin to loop through the given Tweets:

public function filterTweets($tweets = array()){
    $formatted_tweets = array();

    foreach($tweets as $key => $tweet){

    }
}

For each Tweet, there are a few array keys we are interested in:

screen_name: this is the handle of the person posting the Tweet
profile_image_url: as it says on the tin!
id: the ID of the Tweet
date: the date the Tweet was posted
text: the actual Tweet

These are the key elements we will be converting in to a usable array. Lets jump in to the Tweets array and start filtering. We are going to use 2 common PHP functions here to help us filter, the first one is substr(); which allows us to remove a number of characters from a string for comparison purposes and stripos which looks in a string for a given bit of text. Stripos is similar to strpos but it is case insensitive (hashtags are case insensitive!).

public function filterTweets($tweets = array()){
    $formatted_tweets = array();

    foreach($tweets as $key => $tweet){
        if((substr($tweet['text'], 0, 3) == "RT ") && ($tweet['retweeted_status']) && (stripos($tweet['retweeted_status']['text'], '#anyexcuse') !== false)){

        }
    }
}

Lets jump through each condition here:

substr($tweet[‘text’], 0, 3) returns the first 3 characters of the Tweet text, we are looking for this to be identical to “RT “.

$tweet[‘retweeted_status’] this a second method to ensure the status IS a retweeted status.

stripos($tweet[‘retweeted_status’][‘text’], ‘#anyexcuse’) this looks for the string #anyexcuse inside $tweet[‘retweeted_status’][‘text’], if it finds the string the function returns true – we are looking for anything but a false response.

These 3 conditions ensure we get the retweeted Tweets, with the hashtag #AnyExcuse.

All that is left is to rebuild the array and return it to the original requester.

public function filterTweets($tweets = array()){
    $formatted_tweets = array();

    foreach($tweets as $key => $tweet){
        if((substr($tweet['text'], 0, 3) == "RT ") && ($tweet['retweeted_status']) && (stripos($tweet['retweeted_status']['text'], '#anyexcuse') !== false)){
            $formatted_tweets[$key]['User'] = array(
                'screen_name' => $tweet['retweeted_status']['user']['screen_name'],
                'profile_image_url' => $tweet['retweeted_status']['user']['profile_image_url'],
            );

            $formatted_tweets[$key]['Tweet'] = array(
                'id' => $tweet['retweeted_status']['id'],
                'date' => date("Y-m-d H:i:s", strtotime($tweet['retweeted_status']['created_at'])),
                'text' => $tweet['retweeted_status']['text']
            );
        }
    }
}

Here we create a multi-dimensional array with sub-arrays for easy reading. The returned array would look something like this:

array(
    'User' => array(
        'screen_name' => 'engagetweet',
        'profile_image_url' => '<img class="redactor-autoparser-object" src="https://pbs.twimg.com/profile_images/3091358422/10c1861846dd45d2bba96dd9e98fb8ac_bigger.png">'
    ),
    'Tweet' => array(
        'id' => '1',
        'date' => '2013-10-31 11:59:00',
        'text' => 'This is a Tweet!'
    )
);

And that covers the technical PHP class bits! In our #AnyExcuse application we make sure that the getTweets function is run at a maximum of once every 15 minutes as there is a resource limit on the Twitter API. The Tweets are cached to the database. We also run all Tweet text through a parseTweet function to parse all elements in to a URL e.g. any other hashtags, @user and website URLs.

Once you have done this, open your index.php file and at the very top before your < html > tag, pull in the twitter library file and instantiate the Twitter class.

<?php
    require_once('libs/twitter.php');
    $twitter = new Twitter();
?>
...

Now in your < body > tags, we can return the nice neat array of Tweets to use in your application:


    <?php
        $tweets = $twitter->getTweets();
        foreach($tweets as $key => $tweet){
            echo $tweet['Tweet']['id'];
            echo $tweet['Tweet']['date']
            echo $tweet['Tweet']['text'];
            echo $tweet['User']['screen_name'];
            echo $tweet['User']['profile_image_url'];
        }
    ?>

And there you have it! You have now successfully pulled in all Tweets that have been retweeted by your account that have the hashtag #AnyExcuse!