[PHP] Twitter Feed Reader + Caching

Status
Not open for further replies.

Whoo

The Wise One
2,480
2008
282
0
Hey,

Coded something yesterday. Basically it fetches the tweets of someone and saves them in a temporary file which is updated every hour. (You can modify this). It's a quick code mock-up and I wouldn't put it on a production website before testing it.

PHP:
<?php
$username = 'TwitterUserNameHere';
$limit = 5;
$feed = 'http://twitter.com/statuses/user_timeline.rss?screen_name='.$username.'&count='.$limit;

$tweets = file_get_contents($feed);
$tweet = explode("<item>", $tweets);
$tcount = count($tweet) - 1;

for ($i = 1; $i <= $tcount; $i++) {
    $find = array('–', $username);
    $replace = array('-', '');
    
    $endtweet = explode("</item>", $tweet[$i]);
    $title = explode("<title>", $endtweet[0]);
    $content = explode("</title>", $title[1]);
    
    $tweetItem = str_replace($find, $replace, $content[0]);
    $tweetItem = preg_replace('#(http:\/\/([a-zA-Z0-9\.\/]+))#','<a rel="nofollow" href="$1">$1</a>',$tweetItem);

    $mytweets[] = $tweetItem;
}

$tweetout = '<ul>';
while (list(, $v) = each($mytweets)) {
    $tweetout .= "<li>$v</li>";
}
$tweetout .= '</ul>';


$twitterTempFile = 'twitterfeed.temp';

$lastModified = filemtime($twitterTempFile);

if ($lastModified < strtotime("-1 hour")){
    $fh = fopen($twitterTempFile, 'w+') or die('Unable to open file');
    fwrite($fh, $tweetout);
    fclose($fh);
}else{
    $tweetout = file_get_contents($twitterTempFile);
}

echo $tweetout;
Make sure you have a file called twitterfeed.temp in the same directory which is writable (chmod 777). I had to use file_get_contents() because here to make it easy but in the original version I had a curl function there.

Remember, this is just something I put together in a few minutes, it's not written very good (I code better usually lol even if I say so myself).

Oh well, enjoy I guess ;)

+ rep is appreciated if you can use this code ;)
 
Status
Not open for further replies.
Back
Top