Skip to content

Instantly share code, notes, and snippets.

@chrisblakley
Last active April 18, 2016 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisblakley/93bc223f2342aef71ac3 to your computer and use it in GitHub Desktop.
Save chrisblakley/93bc223f2342aef71ac3 to your computer and use it in GitHub Desktop.
Cache Twitter feeds using PHP and JSON
//This can go in main.js or where ever.
jQuery.getJSON('/includes/twitter_cache.php', function(data) { //If using Nebula, the path will be: nebula.site.directory.stylesheet.uri + '/includes/twitter_cache.php'
jQuery.each(data, function(i) {
console.log(data[i]);
});
//Example full implementation:
jQuery('#tweetlink').attr('href', 'https://twitter.com/' + data[0].user.screen_name).text('@' + data[0].user.screen_name);
var tweetTime = new Date(Date.parse(data[0].created_at));
jQuery('#tweet').html(tweetLinks(data[0].text)).append(" <span class='twitter-posted-on'><i class='fa fa-clock-o'></i> " + timeAgo(tweetTime) + "</span>");
});
//Create links from the JSON text.
function tweetLinks(tweet){
var newString = tweet.replace(/(http\S*)/g, '<a href="' + "$1" + '" target="_blank>' + "$1" + '</a>'); //Links that begin with "http"
newString = newString.replace(/#(\S*)/g, '<a href="https://twitter.com/hashtag/' + "$1" + '" target="_blank">#' + "$1" + '</a>'); //Link hashtags
newString = newString.replace(/@(\S*)/g, '<a href="https://twitter.com/' + "$1" + '" target="_blank">@' + "$1" + '</a>'); //Link @username mentions
return newString;
}
//Format the timestamp of the tweet to be relative
function timeAgo(time) { //http://af-design.com/blog/2009/02/10/twitter-like-timestamps/
var system_date = new Date(time);
var user_date = new Date();
var diff = Math.floor((user_date-system_date)/1000);
if (diff <= 1) return "just now";
if (diff < 20) return diff + " seconds ago";
if (diff < 60) return "less than a minute ago";
if (diff <= 90) return "one minute ago";
if (diff <= 3540) return Math.round(diff/60) + " minutes ago";
if (diff <= 5400) return "1 hour ago";
if (diff <= 86400) return Math.round(diff/3600) + " hours ago";
if (diff <= 129600) return "1 day ago";
if (diff < 604800) return Math.round(diff/86400) + " days ago";
if (diff <= 777600) return "1 week ago";
return "on " + time;
}
<?php
/*
* Will need to create an app in Twitter: https://apps.twitter.com/
*
* Note: To avoid having to use this file, generate a bearer token here: http://gearside.com/nebula/documentation/utilities/twitter-bearer-token-generator/
*
* Once created, use the consumer key and consumer secret in the variables below.
* Then, load this file in a browser to receive a Twitter Bearer Token (which will be used in the next file).
*/
$ch = curl_init();
//set the endpoint url
curl_setopt($ch,CURLOPT_URL, 'https://api.twitter.com/oauth2/token');
// has to be a post
curl_setopt($ch,CURLOPT_POST, true);
$data = array();
$data['grant_type'] = "client_credentials";
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
// here's where you supply the Consumer Key / Secret from your app:
$consumerKey = 'consumer_key_here';
$consumerSecret = 'consumer_secret_here';
curl_setopt($ch,CURLOPT_USERPWD, $consumerKey . ':' . $consumerSecret);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
// show the result, including the bearer token (or you could parse it and stick it in a DB)
print_r($result);
<?php
/*
* !!! Before testing this file: Create a new directory in the same directory as this file called "cache". Inside that directory, create a file (with no extension) called "twitter-cache".
* Change the bearer token below to be the same as the one generated from the previous file!
* Change the username below to be the desired Twitter username, and change the number of tweets as needed.
* Default cache is 10 minutes (600), but can be changed.
* Either run this file directly, or trigger it via JavaScript (the next file).
*/
error_reporting( 0 ); //Don't let any php errors ruin the feed
$number_tweets = 4;
//Only choose one $feed type from below. Remove or comment out the other(s).
//This is for a single username
$username = 'username'; //No @ symbol
$feed = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=$username&count=$number_tweets&include_rts=1";
//This is for a list (which pulls several users' tweets).
$list_owner_username = 'username'; //No @ symbol
$list_name = 'listname'; //AKA "slug"
//$feed = "https://api.twitter.com/1.1/lists/statuses.json?slug=$list_name&owner_screen_name=$list_owner_username&count=$number_tweets&include_rts=1";
$cache_file = dirname(__FILE__) . '/cache/twitter-cache';
$modified = filemtime( $cache_file );
$now = time();
$interval = 600; //Ten minutes (600). May need to change to lower if/when troubleshooting
// check the cache file
if ( !$modified || (($now-$modified) > $interval) ) {
$bearer = 'AAAAAAAAAAAAAAAAAAAAA...';
$context = stream_context_create(array(
'http' => array(
'method'=>'GET',
'header'=>"Authorization: Bearer " . $bearer
)
));
$json = file_get_contents( $feed, false, $context );
if ( $json ) {
$cache_static = fopen( $cache_file, 'w' );
fwrite( $cache_static, $json );
fclose( $cache_static );
}
}
header( 'Cache-Control: no-cache, must-revalidate' );
header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
header( 'Content-type: application/json' );
$json = file_get_contents( $cache_file );
echo $json;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment