How To Display Tweets of Different Users
When I redesigned this blog I wanted to show recent tweets about MooTools. There are a number of available options to do that: either show the tweets of @mootools or show anyone who mentions #MooTools. While the first approach seemed to be too boring, the search also comes with its problems: it is completely unmoderated. Anyone would be able to put anything on the sidebar of my blog just by mentioning MooTools. As all MooTools developers have accounts on twitter the logical solution to me was to show the latest tweets of them. I'm going to show you the smartest, cleanest and easiest way to do that.
Interlude
Before we get started I need to make you aware that you have been directed to my new domain. As my old domain has been hijacked please update your feed subscriptions to the new URL. I'm sorry for the inconvenience. 
Let's get started
For the script below I'm making use of the excellent Arc90 Twitter API but I wrap it with my own simple Twitter class which also handles caching in a very basic way. You can find the download at the end of the page but let us have a look at the demo first:
It shows the tweets of all people I'm following plus my own - its exactly the same as my timeline when I go to the twitter website.
Why is this special?
I'm not going the way of fetching my followers and then retrieving their latest tweets but instead I'm using my account data to show my friend's timeline. This is not also faster but it also reduces n requests (the number of followers + 1) to only one.
If you feel like you follow ten people that are worth having their tweets on your website, create a dummy account (for example: mydomaindotcom), follow those ten people and throw in my Twitter class to make the magic happen!
The Class
The class is very easy to use, it exposes two public methods with the same API and a few options.
Methods
- getMyTweets($user, $options) - fetches only the tweets of the specified user
- getForeignTweets($user, $options) - fetches all tweets of the people you follow and those of yourself
Arguments
- $user - an array consisting of a username and password
- name - the username to be used
- password - the password
- $options - optional - an array consisting of additional options
- count (defaults to 2) - the number of tweets to retrieve
- prefix (defaults to Cache/twitter) - the folder prefix to be used for caching, set this to false to disable caching
- ttl (defaults to 600) - the time (in seconds) to cache the tweet
Return Values
Both methods return either an empty array or an array consisting of Twitter messages with the following keys:
- id - the id of the tweet
- name - the user who posted the message
- status - the actual text of the tweet
<?php
/*
Script: Twitter.php
Simple Twitter interaction class
License:
MIT-style license.
Copyright:
Copyright (c) 2009 [Christoph Pojer](http://cpojer.net).
Usage:
[Blog Article](http://cpojer.net/blog/How_To_Display_Tweets_of_Different_Users)
*/
require_once('Assets/Twitter.php');
class Twitter {
public function getMyTweets($user, $options = array()){
return $this->getTweets($user, $options);
}
public function getForeignTweets($user, $options = array()){
return $this->getTweets($user, array_merge($options, array(
'type' => 'friends',
)));
}
protected function getTweets($user, $options = array()){
$options = array_merge(array(
'type' => 'me',
'count' => 2,
'prefix' => 'Cache/twitter',
'ttl' => 600,
), (array)$options);
if(empty($options['type']) || !in_array($options['type'], array('me', 'friends')))
$options['type'] = 'me';
if(empty($user['name']) || empty($user['password'])) return;
$key = $options['prefix'].md5($options['type'].'_'.$options['count'].'_'.$options['ttl'].'_'.$user['name']).'.txt';
$data = empty($options['prefix']) ? null : $this->retrieve($key);
if(!$data){
try{
$twitter = new Arc90_Service_Twitter($user['name'], $user['password']);
$twitter->setSSL(false);
$response = null;
if($options['type']=='me') $response = $twitter->getUserTimeline();
elseif($options['type']=='friends') $response = $twitter->getFriendsTimeline();
$array = json_decode($response->getData(), true);
if($response->isError() || !count($array))
throw new Arc90_Service_Twitter_Exception($response->http_code);
$i = 0;
foreach($array as $status){
if($status['text'][0]=='@') continue; // This excludes replies
$data[] = array(
'id' => $status['id'],
'name' => $status['user']['screen_name'],
'status' => htmlspecialchars($status['text'], ENT_COMPAT, 'UTF-8', false),
);
if(++$i>=$options['count']) break;
}
}catch(Arc90_Service_Twitter_Exception $e){
$data = 'error';
}
if(!empty($options['prefix'])) $this->store($key, $data, $options['ttl']);
}
return $data == 'error' ? array() : $data;
}
protected function retrieve($key){
if(!file_exists($key)) return null;
$content = unserialize(file_get_contents($key));
if(!is_array($content) || empty($content['ttl']) || $content['ttl']<time()) return null;
return $content['data'];
}
protected function store($key, $data, $ttl = 600){
$content = array(
'data' => $data,
'ttl' => time()+$ttl,
);
file_put_contents($key, serialize($content));
}
}
Usage
With the above methods and options it is easy to compose a usable script. Have a look at the code below, which outputs tweets in HTML.
<?php
require_once('Twitter.php');
$t = new Twitter;
foreach($t->getForeignTweets(array(
'name' => 'username',
'password' => 'password',
), array(
'count' => 10,
)) as $tweet)
echo '<div class="stack">
<a href="http://twitter.com/'.$tweet['name'].'">@'.$tweet['name'].'</a>
<a class="tweet" href="http://twitter.com/'.$tweet['name'].'/status/'.$tweet['id'].'">'.$tweet['status'].'</a>
</div>';
Download
Have fun with the class! Everything is bundled and set up, just have a look at the tweets.phps file as an example and write your own code to display tweets! (Btw. don't forget to set the CHMOD to 777 for the Cache directory)
Why is interacting with the Twitter API in JavaScript bad?
There are several reasons why I do not like fetching data from Twitter (or: any API) via JavaScript. With the first being that you have no ability to cache the requests and possible limits of requests per hour, the more obvious reason in the plugin above is that you need the password to "login" to your account. There is no secure way you could do that with JavaScript.
You will always find me advocating the use of serverside caching technologies and pre-parsing the output to put it in a - for your application - usable format. It is much more scalable. End of discussion.
Leave a comment
7 comments on How To Display Tweets of Different Users
Nike Dunk posted on 9th March 2010
yandi posted on 6th March 2010
website, you will find the cheppest and high quality products from here.<a title="GHD Pretty" href="http://www.sweetv.com/GHD-Pretty-
sweetv-197.html" alt="GHD Pretty">GHD Pretty</a> <a title="GHD Pure Styler" href="http://www.sweetv.com/GHD-Pure-Styler-sweetv-196.html"
alt="GHD Pure Styler">GHD Pure Styler</a> <a title="GHD Purple Gift" href="http://www.sweetv.com/GHD-Purple-Gift-sweetv-195.html" alt="GHD
Purple Gift">GHD Pur
Carter Cole posted on 26th January 2010
darubillah posted on 13th January 2010
thankyou for the script I will try it soon
Well I dont understand what do you mean by that your domain is hi jacked,
does it mean that you can now never use your old domain?? & some transfer it to his name??
best uggs posted on 30th December 2009
<a href="http://www.bestuggs.org/">best ugg boots</a>
<a href="http://www.bestuggs.org/">ugg outlet</a>
<a href="http://www.bestuggs.org/">buy ugg</a>
<a href="http://www.bestuggs.org/">top ugg</a>
Tim posted on 23rd October 2009
Thanks,
http://www.jerseys-buy.com/soccer-jersey/Shop-by-Country/USA.html USA jersey