Retrieve favourite tweets in PHP for Twitter API 1.1

30 July, 2013 by Tom Elliott

To retrieve the latest set of favourite tweets (from any public user) is a fairly straightforward process that uses the “GET favourites/list” method from Twitter’s REST API 1.1.

First of all however you’ll need to set up an ‘app’ at the Twitter developer portal, get a load of keys, and use an OAuth library that will take care of all the authentication required. Head over to my twitter feed authentication post for a step by step.

After you’ve got the authentication working, it is then a simple case of switching the end point to https://api.twitter.com/1.1/favorites/list.json,

Line 19 in the authentication tutorial now becomes:

$tweets = $connection->get("https://api.twitter.com/1.1/favorites/list.json?screen_name=".$twitteruser."&count=".$notweets);

The full favourite tweet PHP authentication is below:

<?php
session_start();
require_once("twitteroauth/twitteroauth/twitteroauth.php"); //Path to twitteroauth library

$twitteruser = "twitterusername";
$notweets = 30;
$consumerkey = "12345";
$consumersecret = "123456789";
$accesstoken = "123456789";
$accesstokensecret = "12345";

function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret) {
  $connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
  return $connection;
}

$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);

$tweets = $connection->get("https://api.twitter.com/1.1/favorites/list.json?screen_name=".$twitteruser."&count=".$notweets);

echo json_encode($tweets);
?>

It is important to note rate limiting for tweet favourites here. Unlike regular user timeline endpoints which has a window of 180 requests per 15 minute window, the GET favourites/list rate limit is much lower with a limit of 15 requests per 15 minute window (per access token). This means you’ll almost certainly want to cache your tweets to a local file and then setup a scheduled task (or cron job) to request the PHP file on a regular basis. An interval of 5 minutes would keep you’re favourites list fresh without triggering the rate limiting. Checkout my twitter feed caching tutorial for more details.

Now that you’ve got your favourite tweets outputting as JSON format, you might want to create a fully styled twitter feed. As the JSON output for tweet favourites is exactly the same as with a regular user timeline, my jquery twitter feed tutorial will integrate easily with this favourite tweet output.



Creating a Twitter Search & Analytics tool »