Beware this content is over 7 years old and considered stale. It may no longer be accurate and/or reflect the understanding of the author but remains here for reference only. Please keep this in mind as you use this content.

During a recent project I needed a script to retrieve some real-time data from a Twitter account and display the results on the homepage.

After a quick search I came across a helpful PHP script by Joost de Valk. Much of the code below is based on his original script, so all credit to him.

My only problems with the script was that it was a little confusing as to what to insert where and it lacked a handy demo page (although if you scroll to the footer you can see it in action) or a handy download button where I can grab the files.

The following script uses the fantastic Snoopy PHP Class which simulates a web browser and allows us to retrieve the required data to be processed.

http://sourceforge.net/projects/snoopy/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
// get latest tweet and number of followers
function get_tweet_info(){
require_once('class-snoopy.php');
$tweet = get_option('lasttweet');
$url = 'http://twitter.com/statuses/user_timeline/Dreyer.json?count=1';
if($tweet['lastcheck'] &lt; (mktime() - 60)){
$snoopy = new Snoopy;
$result = $snoopy-&gt;fetch($url);
if($result){
$twitterdata = json_decode($snoopy-&gt;results,true);
$i = 0;
while($twitterdata[$i]['in_reply_to_user_id'] != ''){
$i++;
};
$pattern = '/\@([a-zA-Z]+)/';
$replace = '[@\1](http://twitter.com/)';
$output = preg_replace($pattern, $replace, $twitterdata[$i]['text']);
//$format = 'F j, Y, H:i:s';
$format = 'F j, Y';
$tweet['lastcheck'] = mktime();
$tweet['data'] = make_clickable($output);
$tweet['date'] = $twitterdata[0]['created_at'];
$tweet['rawdata'] = $twitterdata;
$tweet['followers'] = $twitterdata[0]['user']['followers_count'];
$tweet['friends'] = $twitterdata[0]['user']['friends_count'];
update_option('lasttweet', $tweet);
}else{
//$output = 'Twitter API not responding.';
$output = '';
};
};
echo '
<div class="latesttweet">
### Latest Tweet on '.date($format, strtotime($tweet["date"])).'
'.$tweet['data'].'
We have '.$tweet['friends'].' friends and ['.$tweet['followers'].' followers](http://twitter.com/Dreyer "Follow us on Twitter!") on Twitter. Why not follow us too?</div>
';
//$output = make_clickable($output);
/*
if(!$output){
echo '<!-- No Twitter data was retrieved. API is not responding. -->';
}else{
};
*/
};
?>

Hope that little snippet of information helps someone. An explanation may follow depending on interest.