Display tweets on your website using PHP and jQuery

Placing objeThe latest API from Twitter requires authentication to display tweets. Here's how to do so with PHP and easily display them with javascriptcts within this box opens a hidden trapdoor...

twitter,middleman,php,javascript

In Twitter's latest version of its API, you must now authenticate in order to pull tweets. Yes even public ones. Yes, even your own. I recently had to cross the bridge on a site I was building using the static site generator Middleman. And while the final solution was pretty easy to set up, finding that solution took a bit of time, so I figured I'd post my solution here to hopefully save others the trouble. This tutorial is not Middleman specific, but I include that step below.

Middleman is ruby based, and while it was a breeze to set up, I know nothing about Ruby when it comes to extending the core functionality. PHP is much easier for me to wrap my head around, but to get this working in Middleman, I recommend this gem, which gets PHP running with no trouble.

Once you're running PHP, there are a number of PHP libraries out there that take the grunt work out of authenticating and accessing Twitter's API. I tried and failed with a couple, but I found this one to be super easy. I just made a folder within Middleman's 'source' directory called 'php', and dropped in the file TwitterAPIExchange.php.

From there, head over to apps.twitter.com and register a new application. You can put the URL of your final website address in the Website field (even if you're working locally), and leave the callback URL blank - we won't need it for this tutorial. Once this is set up, click on the API Keys tab, and generate an API Key and API Secret. Next, generate an access token and access secret on the same page, below.

Then we can write a PHP script to access the tweets. I made a file called getTweets.php, and put it alongside the TwitterAPIExchange.php file. Here's what getTweets.php looks like:


  <?php

  require_once('TwitterAPIExchange.php');

  $settings = array(
      'oauth_access_token' => "[access token here]",
      'oauth_access_token_secret' => "[access secret here]",
      'consumer_key' => "[API key here]",
      'consumer_secret' => "[API secret here]"
  );

  $url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
  $getfield = '?screen_name=[YOUR SCREEN NAME HERE]&count=[NUMBER OF TWEETS TO PULL HERE]';
  $requestMethod = 'GET';
  $twitter = new TwitterAPIExchange($settings);
  echo $twitter->setGetfield($getfield)
               ->buildOauth($url, $requestMethod)
               ->performRequest();


  ?>
  

In the code above, replace everything in square brackets (including the brackets themselves), with all of the authentication credentials you just set up in your twitter app. Put in the screen name you want to pull tweets from, and in the count field, put in the number of tweets you want to pull (it will grab the most recent). Notice that the $url we've set up here is the user_timeline.json.

Now that this is set up, we can write something in Javascript to pull the tweets. In middleman, I set up a 'js' directory in the 'source' directory, and built a file called 'tweets.js' - here's what that file looks like:


  $.getJSON("php/getTweets.php",function(data){
    for (var i=0; i<data.length;i++){
      var tweetText = data[i].text;
      var tweetTimestamp = data[i].created_at;
      var tweetDate = moment(tweetTimestamp).twitterLong()
      var $tweetItem = $('<div class="item"><p class="timestamp">' + tweetDate + '</p><p class="tweet">' + tweetText + '</p></div>');
      $('#tweet-container').append($tweetItem);
    }
  });
  

Here, I'm just using jQuery's getJSON method in order to call the PHP script we just configured. If everything's set up correctly, we'll be able to pull our latest tweets and return the data to our script. For my twitter module, I'm just looping through all the returned data, and grabbing the tweet itself (data[i].text), and the time it was posted (data[i].created_at). I'm taking this information, and dumping it into a div, and appending that div to a parent container. I'll let you figure out how you want to display all the tweets, but I should point out the manipulations I'm making to the date.

Twitter's API returns a timestamp which, on its own, is not really readable, so it needs to be converted to something intelligible. There's a number of ways to do this, but here again, I've taken the easy way out by downloading a library called moment, which you can find here. My client's request was to have the date in the "x minutes ago" format, so in order to do so I downloaded another small script, which uses moment to perform this date calculation, called moment-twitter. Include both of these scripts before the javascript above, so that when you call moment (tweetDate = moment(tweetTimestamp).twitterLong()), you can make the conversion from a timestamp, to the time since the present when the tweet was created.

So that's it - not too technical, just a lot of pieces to tie together which can sometimes be frustrating. Hope this helps anyone who was stuck like I was.