Twitter recently updated its API and abandoned support for v1.0 of its API. If you're wanting to display your latest tweets, you'll need to use the new version of the API.

Twitter API Developers

The new version of Twitter's API now means you cannot search or retrieve user tweets without being authenticated. Twitter have also introduced restrictions on the number of connections per minute than an application can make. Twitter have also removed support for any XML code and therefore everything is returned as JSON.

1. Create and Authentication an Application

We need to grant Twitter permission to the account that we want to retrieve tweets for. To do this, we need to create a developers application and create an access token for ourselves.

Go to the Twitter Developer area - https://dev.twitter.com

Select 'My Applications' from the right-most dropdown and then 'Create new application'

Fill in the details in the form to create your application. Once you save, you'll re redirected to the application page

Go to the 'OAuth Tool' tab - you'll need to keep a note of the consumer key, consumer secret, access token, access token secret. If you can't see the access token, you need to go the the application overview and click 'Create access token'

2. Download the Required TwitterOAuth

The PHP library TwitterOAuth is the most commonly available PHP class. You can download it from PHP TwitterOAuth GitHub

There are several alternative classes/connectors available for different languages - but we're going to focus on PHP.

3. Pull It Altogether

Now we need to fire up TwitterOAuth, create a connection to the API and then retrieve the tweets. You can use the code below, create a new file 'Twitter.php':

# Load Twitter class
require_once('TwitterOAuth.php');
# Define constants
define('TWEET_LIMIT', 5);
define('TWITTER_USERNAME', 'YOUR_TWITTER');
define('CONSUMER_KEY', 'YOUR_KEY');
define('CONSUMER_SECRET', 'YOUR_SECRET_KEY');
define('ACCESS_TOKEN', 'YOUR_TOKEN');
define('ACCESS_TOKEN_SECRET', 'YOUR_TOKEN_SECRET');
# Create the connection
$twitter = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
# Migrate over to SSL/TLS
$twitter->ssl_verifypeer = true;
# Load the Tweets
$tweets = $twitter->get('statuses/user_timeline', array('screen_name' => TWITTER_USERNAME, 'exclude_replies' => 'true', 'include_rts' => 'false', 'count' => TWEET_LIMIT));
# Example output
if(!empty($tweets)) {
    foreach($tweets as $tweet) {
        # Access as an object
        $tweetText = $tweet['text'];
        # Make links active
        $tweetText = preg_replace("#(http://|(www.))(([^s<]{4,68})[^s<]*)#", '<a href="http://$2$3" target="_blank">$1$2$4</a>', $tweetText);
        # Linkify user mentions
        $tweetText = preg_replace("/@(w+)/", '<a href="http://www.twitter.com/$1" target="_blank">@$1</a>', $tweetText);
        # Linkify tags
        $tweetText = preg_replace("/#(w+)/", '<a href="http://search.twitter.com/search?q=$1" target="_blank">#$1</a>', $tweetText);
        # Output
        echo $tweetText;
    }
}

4. Wrapping It Up

Wherever you want your Tweets to display, just include 'Twitter.php' and your tweets will be displayed. You can change the constants to change the limit of tweets to retrieve and you can remove the code to turn mentions and tags into links.

If you want to use jQuery to load your tweets through AJAX, just set the URL to point to your 'Twitter.php' and return a JSON object as such:

# Put this after fetching Tweets
$twitter = '';
# Create the HTML output
if(!empty($tweets)) {
    foreach($tweets as $tweet) {
        $twitter .= '<article>
            <aside class="avatar">
                <a href="http://twitter.com/'.$tweet['from_user'].'" target="_blank">
                    <img alt="'.$tweet['from_user'].'" src="'.$tweet['user']['profile_image_url'].'" />
                </a>
            </aside>
            <p>'.$tweet['created_at'].'</p>
            <p>'.$tweet['text'].'</p>
        </article>';
    }
}

Now you can create a Javascript call:

// You can use JSON here and just return the raw tweets, but we're processing it on the server instead and just returning the HTML structure
$.ajax({
    dataType: "html",
    url: 'Twitter.php',
    success:function(returnHTML){
        $('#tweets').html(returnHTML);
    }
});

5. Update for SSL

As of 14th January 2014, Twitter now enforces that connections are made through SSL/TLS. To update your existing code so that it'll still load your Tweets, you'll need to update the TwitterOAuth.php class. You'll find on line 193 the function 'http', you'll need to add the following code before the switch statement and ensure the certificate in the download is in the same directory.

We have uploaded the revised TwitterOAuth.php class and its certificate, you can download them below.

# Find this line 
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
# Add after these two new lines
curl_setopt($connection, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($connection, CURLOPT_CAINFO, __DIR__."/ca-bundle.crt");

You can download the security certificate below, just drop it into a directory and then replace the directory path above.


Download Certificate


Image Source: Digital Trends

25
Ignite your brand, utilise user-generated content no matter where you or your audience are ›