Display your latest tweet(s) on your website

I recently worked with Magnify Digital on a website for a very interesting group of people in the Fraser Valley. These folks are concerned about Air Quality and thus have come up with a website and community to address these issues.

A big part of the website was the social media aspect. Thus facebook, twitter and youtube feature prominently on the website. There are plenty of WordPress plugins that allow you to display your latest tweets, but I wanted a simpler solution. The following piece of code proved to be just what I needed:


<?php
$username = "yourTwitterUsername";
$limit = "1"; // Number of tweets to pull in.

/* These prefixes and suffixes will display before and after the entire block of tweets. */
$prefix = ""; // Prefix - some text you want displayed before all your tweets.
$suffix = ""; // Suffix - some text you want displayed after all your tweets.
$tweetprefix = "<p>"; // Prefix - some text you want displayed before each tweet.
$tweetsuffix = "</p>"; // Suffix - some text you want displayed after each tweet.

$feed = "http://search.twitter.com/search.atom?q=from:" . $username . "&rpp=" . $limit;

function parse_feed($feed, $prefix, $tweetprefix, $tweetsuffix, $suffix) {

$feed = str_replace("&lt;", "<", $feed);
$feed = str_replace("&gt;", ">", $feed);
$feed = str_replace("&quot;", "\"", $feed);
$feed = str_replace("&apos;", "'", $feed);
$clean = explode("<content type=\"html\">", $feed);

$amount = count($clean) - 1;

echo $prefix;

for ($i = 1; $i <= $amount; $i++) {
$cleaner = explode("</content>", $clean[$i]);
echo $tweetprefix;
echo $cleaner[0];
echo $tweetsuffix;
}

echo $suffix;
}

$twitterFeed = file_get_contents($feed);
parse_feed($twitterFeed, $prefix, $tweetprefix, $tweetsuffix, $suffix);
?>

2 Responses to “Display your latest tweet(s) on your website”

  1. annie says:

    this is fabulous – thank you for your great code! quick question – how do i get a prefix to contain HTML? also, is it possible to pull tweets from a twitter list?

  2. Christine says:

    Hello Annie,

    In the code provided, the following line – $tweetprefix = “”; should allow you to add more html.

    As for your second question, I’m really not sure. I’ve never tried or heard of that.