skip navigation

PHP: Displaying Twitter Search Results in HTML

Here's a new use for our RSS Feed Reader - displaying content returned by the Twitter API. In this article we are simply fetching and presenting the most recent 'tweets' containing a particular string, but there's no reason why the same code can't be used for other RSS content returned by Twitter.

Fetching the feed contents from Twitter

The first step is to define our parameters:

<?PHP if(!isset($_GET['q']) || !$q = $_GET['q']) $q = 'twitter'; $NUMITEMS = 10; $BLOGURL = "http://search.twitter.com/search.rss?q=" . urlencode($q) , "&rpp=$NUMITEMS"; $TIMEFORMAT = "j F Y, g:ia"; $CACHEFILE = "/tmp/" . md5($BLOGURL); $CACHETIME = 0.5; // hours

You can see from the first line that this script accepts a single $_GET parameter $q defining the search string. If this variable is not set then the default search is for 'twitter'. The other parameters should be self-explanatory.

To do a search on Twitter we just send an HTTP request to their search script including the format (in this case 'rss') and the query string. Other more advanced options (see References below) are also available. For our purposes just the rpp (number of tweets to return per page) parameter is enough. No authentication is necessary as we're only reading public content, but it is rate limited.

For security it's a good idea to expand any 'shortened' urls in the results. That way people know what they're clicking on. We do this using curl and a crafty regular expression that detects most known url-shortening services:

# Original PHP code by Chirp Internet: www.chirp.com.au # Please acknowledge use of this code by including this header. function expandLinks(&$input) { // links matching the following regular expressions will be checked for redirects and expanded $domains = array( '[a-z0-9]{2,3}\.[a-z]{2}', '[a-z]{3,4}url\.com' ); if(preg_match_all("@http://((" . implode("|", $domains) . ")/[-a-z0-9]+)@i", $input, $matches)) { $matches = array_unique($matches[1]); foreach($matches as $shorturl) { $command = "curl --head " . escapeshellarg($shorturl) . " | awk '($1 ~ /^Location/){print $2}'"; if($expandedurl = exec($command)) { $input = str_replace("http://$shorturl", htmlspecialchars($expandedurl), $input); } } } }

We could also just try to expand every URL detected, but then you're making a lot of unnecessary HEAD requests for those links that pass through Twitter unshortened.

Important: Using the PHP Curl library is also possible and might be necessary if you're using Windows. The script presented above requires command-line curl access and the awk function. You can find a script that uses PHP Curl under References below.

Now we need a way to download and store (cache) the feed contents. We do this using a simple function:

function updateFeed() { global $BLOGURL, $CACHEFILE; ini_set('user_agent', "TheArtOfWeb (http://{$_SERVER['HTTP_HOST']})"); if($feed_contents = file_get_contents($BLOGURL)) { // expand shortened urls expandLinks($feed_contents); // write feed contents to cache file $fp = fopen($CACHEFILE, 'w'); fwrite($fp, $feed_contents); fclose($fp); } }

The updateFeed function when called simply downloads and stores the raw RSS file contents. Note that before making the API request to Twitter we are setting the user agent. You don't have to set a user agent, but if you don't your requests can be rate-limited.

Displaying the search results in HTML format

In the next section we display a short paragraph introducing the search results. Both the search string and the last modified date of the cached file are displayed:

echo "<p>Read the latest tweets mentioning <b>$q</b> as of "; if(file_exists($CACHEFILE)) { echo date('g:ia', filemtime($CACHEFILE)) . ' local time'; } else { echo 'right now'; } echo ":</p>\n\n";

If no cached file exists for this query the updateFeed function is called to fetch it for the first time.

// download the feed iff cached version is missing if(!file_exists($CACHEFILE)) updateFeed();

Finally we're ready to display the search results on the page. This section is almost identical to that introduced in previous articles, the only difference being that it's been customised specifically for Twitter content:

include "class.myrssparser.php"; $rss_parser = new myRSSParser($CACHEFILE); // read feed data from cache file $feeddata = $rss_parser->getRawOutput(); extract($feeddata['RSS']['CHANNEL'][0], EXTR_PREFIX_ALL, 'rss'); // display feed items if($rss_ITEM) { echo "<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\">\n"; foreach($rss_ITEM as $itemdata) { preg_match("/^(.*)@twitter\.com \((.*)\)$/", $itemdata['AUTHOR'], $regs); list($foo, $author, $name) = $regs; echo "<tr>\n"; echo "<td><a title=\"$name\" href=\"http://twitter.com/$author\" target=\"_blank\"><img src=\"{$itemdata['GOOGLE:IMAGE_LINK']}\" width=\"48\" height=\"48\" border=\"0\" alt=\"$author\"></a></td>\n"; echo "<td><p><a href=\"http://twitter.com/$author\" target=\"_blank\">$author</a>: "; echo str_replace('<a ', '<a target="_blank" ', stripslashes($itemdata['DESCRIPTION'])); echo "<br>\n"; echo "<small>"; echo date($TIMEFORMAT, strtotime($itemdata['PUBDATE'])); echo " <a href=\"{$itemdata['GUID']}\" target=\"_blank\">View Tweet</a>"; echo "</small>"; echo "</p></td>\n"; echo "</tr>\n"; } echo "</table>\n\n"; } ?>

The output, as you can probably work out, will be a two-column HTML table displaying the users twitter icon, the update text and timestamp. We've also included some links where appropriate.

As a final step the following code should be placed right at the end of the page after all the HTML has been displayed:

<?PHP // download the feed iff cached version is too old if((time() - filemtime($CACHEFILE)) > 3600 * $CACHETIME) { flush(); updateFeed(); } ?>

The function of this code and the reason for placing it at the end of the page has been described in a previous article.

Sample output of Twitter search results

Here you can see the output of this script more or less exactly as presented. All we've done is added some smilies:

Read the latest tweets mentioning twitter as of right now:

YanaNoveey

YanaNoveey: Ok..guys follow twitter anggota antiRM yuk → @hanafiiiiiii @Aruf @gilangahmadt okeh? @Aprilia_Dian @AmelLiaVioletta @chrisninacrkerz
4 February 2012, 9:07am

TxusMartinez

TxusMartinez: RT @StefanLLA: @johannagara Hälsningar från Luleå! http://t.co/BWv25aPt
4 February 2012, 9:07am

GabyCowleyx

GabyCowleyx: RT @HarrysKiss: Niall with his braces RT if you thought Niall's smile was perfectly fine before http://t.co/AQ7hVL0x
4 February 2012, 9:07am

tweetlike_CARI

tweetlike_CARI: It's sad how u could just teach @imPRETTYPEE stale ass on twitter , like I didn't text her . I remember when u was a virgin to twitter !!
4 February 2012, 9:07am

Rinoooooyy

Rinoooooyy: RT @FunnySolo: Once Upon A Time....I used to sleep. Then this thing called “Twitter” happened
4 February 2012, 9:07am

alllove1D

alllove1D: RT @1Ds_hugdealer: RT if you can guess who's who! http://t.co/uO1gofs8
4 February 2012, 9:07am

ShawtMonFTF

ShawtMonFTF: "@ChineyyLynn: so then come box me chizzo and stop tuff chat over twitter" funniest thing chizzo WILL do it. Ha. Take dat.
4 February 2012, 9:07am

kaaay0402

kaaay0402: RT @news2ch_visca: twitterで有吉に付きまとってるミザリー女が病みすぎてて怖すぎると話題にhttp://t.co/WVtN76DH via @news2ch_visca
4 February 2012, 9:07am

bea_m_s

bea_m_s: RT @_Madridistas_: ORGULLO MADRIDISTA http://t.co/FXSQKgeT
4 February 2012, 9:07am

ArmyForJustin

ArmyForJustin: RT @BlameHarry: Facebook: I love sandwiches. Friends: Yeah nobody cares - Twitter: I love sandwiches. Followers: OMFG me too. White or whole grain?
4 February 2012, 9:07am

This script is experimental so you use it at your own risk. Please send questions and comments via the Feedback link below.

Contents of the Twitter search RSS Feed

Here you can see exactly what kind of data we're receiving back from Twitter in RSS format:

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:google="http://base.google.com/ns/1.0" xmlns:openSearch="http://a9.com/-/spec/opensearch/1.1/" xmlns:media="http://search.yahoo.com/mrss/" xmlns:twitter="http://api.twitter.com/"><channel><title>twitter - Twitter Search</title><description>twitter - Twitter Search</description><link>http://search.twitter.com/search?q=twitter</link><twitter:refresh_url>http://search.twitter.com/search.rss?since_id=165708051003875328&amp;q=twitter</twitter:refresh_url><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><openSearch:itemsPerPage>10</openSearch:itemsPerPage><item><title>Ok..guys follow twitter anggota antiRM yuk &#x2192; @hanafiiiiiii @Aruf @gilangahmadt okeh? @Aprilia_Dian @AmelLiaVioletta @chrisninacrkerz</title><link>http://twitter.com/YanaNoveey/statuses/165708051003875328</link><description>Ok..guys follow &lt;em&gt;twitter&lt;/em&gt; anggota antiRM yuk &#x2192; @&lt;a class=" " href="http://twitter.com/hanafiiiiiii"&gt;hanafiiiiiii&lt;/a&gt; @&lt;a class=" " href="http://twitter.com/Aruf"&gt;Aruf&lt;/a&gt; @&lt;a class=" " href="http://twitter.com/gilangahmadt"&gt;gilangahmadt&lt;/a&gt; okeh? @&lt;a class=" " href="http://twitter.com/Aprilia_Dian"&gt;Aprilia_Dian&lt;/a&gt; @&lt;a class=" " href="http://twitter.com/AmelLiaVioletta"&gt;AmelLiaVioletta&lt;/a&gt; @&lt;a class=" " href="http://twitter.com/chrisninacrkerz"&gt;chrisninacrkerz&lt;/a&gt;</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/YanaNoveey/statuses/165708051003875328</guid><author>YanaNoveey@twitter.com (Ratyazlundtz_&#x263a;)</author><media:content type="image/jpg" height="48" width="48" url="http://a3.twimg.com/profile_images/1692136434/Foto0897_normal.jpg"/><google:image_link>http://a3.twimg.com/profile_images/1692136434/Foto0897_normal.jpg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item><item><title>RT @StefanLLA: @johannagara H&#xe4;lsningar fr&#xe5;n Lule&#xe5;! http://t.co/BWv25aPt</title><link>http://twitter.com/TxusMartinez/statuses/165708050894815232</link><description>RT @&lt;a class=" " href="http://twitter.com/StefanLLA"&gt;StefanLLA&lt;/a&gt;: @&lt;a class=" " href="http://twitter.com/johannagara"&gt;johannagara&lt;/a&gt; H&#xe4;lsningar fr&#xe5;n Lule&#xe5;! &lt;a href="http://t.co/BWv25aPt"&gt;http://t.co/BWv25aPt&lt;/a&gt;</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/TxusMartinez/statuses/165708050894815232</guid><author>TxusMartinez@twitter.com (Txus Mart&#xed;nez)</author><media:content type="image/jpg" height="48" width="48" url="http://a0.twimg.com/profile_images/1249545500/154984_176275455735037_132187376810512_523845_1532818_n_normal.jpg"/><google:image_link>http://a0.twimg.com/profile_images/1249545500/154984_176275455735037_132187376810512_523845_1532818_n_normal.jpg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item><item><title>RT @HarrysKiss: Niall with his braces :) RT if you thought Niall's smile was perfectly fine before http://t.co/AQ7hVL0x</title><link>http://twitter.com/GabyCowleyx/statuses/165708050768990208</link><description>RT @&lt;a class=" " href="http://twitter.com/HarrysKiss"&gt;HarrysKiss&lt;/a&gt;: Niall with his braces :) RT if you thought Niall's smile was perfectly fine before &lt;a href="http://t.co/AQ7hVL0x"&gt;http://t.co/AQ7hVL0x&lt;/a&gt;</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/GabyCowleyx/statuses/165708050768990208</guid><author>GabyCowleyx@twitter.com (Gaby Styles &#x2665;)</author><media:content type="image/jpg" height="48" width="48" url="http://a1.twimg.com/profile_images/1776297672/Bro_s_normal.jpeg"/><google:image_link>http://a1.twimg.com/profile_images/1776297672/Bro_s_normal.jpeg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item><item><title>It's sad how u could just teach @imPRETTYPEE stale ass on twitter , like I didn't text her . I remember when u was a virgin to twitter !!</title><link>http://twitter.com/tweetlike_CARI/statuses/165708050735439872</link><description>It's sad how u could just teach @&lt;a class=" " href="http://twitter.com/imPRETTYPEE"&gt;imPRETTYPEE&lt;/a&gt; stale ass on &lt;em&gt;twitter&lt;/em&gt; , like I didn't text her . I remember when u was a virgin to &lt;em&gt;twitter&lt;/em&gt; !!</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/tweetlike_CARI/statuses/165708050735439872</guid><author>tweetlike_CARI@twitter.com (Cari Poppins ! &#xe418;)</author><media:content type="image/jpg" height="48" width="48" url="http://a2.twimg.com/profile_images/1786349224/image_normal.jpg"/><google:image_link>http://a2.twimg.com/profile_images/1786349224/image_normal.jpg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item><item><title>RT @FunnySolo: Once Upon A Time....I used to sleep. Then this thing called &#x201c;Twitter&#x201d; happened</title><link>http://twitter.com/Rinoooooyy/statuses/165708050295029760</link><description>RT @&lt;a class=" " href="http://twitter.com/FunnySolo"&gt;FunnySolo&lt;/a&gt;: Once Upon A Time....I used to sleep. Then this thing called &#x201c;&lt;em&gt;Twitter&lt;/em&gt;&#x201d; happened</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/Rinoooooyy/statuses/165708050295029760</guid><author>Rinoooooyy@twitter.com (L&#x3a3;OP&#x25b2;RD &#x2666;)</author><media:content type="image/jpg" height="48" width="48" url="http://a0.twimg.com/profile_images/1786771540/lawa_normal.jpg"/><google:image_link>http://a0.twimg.com/profile_images/1786771540/lawa_normal.jpg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item><item><title>RT @1Ds_hugdealer: RT if you can guess who's who! http://t.co/uO1gofs8</title><link>http://twitter.com/alllove1D/statuses/165708049783332865</link><description>RT @&lt;a class=" " href="http://twitter.com/1Ds_hugdealer"&gt;1Ds_hugdealer&lt;/a&gt;: RT if you can guess who's who! &lt;a href="http://t.co/uO1gofs8"&gt;http://t.co/uO1gofs8&lt;/a&gt;</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/alllove1D/statuses/165708049783332865</guid><author>alllove1D@twitter.com (love onedirection &#xab;3)</author><media:content type="image/jpg" height="48" width="48" url="http://a2.twimg.com/profile_images/1756719898/image_normal.jpg"/><google:image_link>http://a2.twimg.com/profile_images/1756719898/image_normal.jpg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item><item><title>"@ChineyyLynn: LOL so then come box me chizzo and stop tuff chat over twitter" funniest thing chizzo WILL do it. Ha. Take dat.</title><link>http://twitter.com/ShawtMonFTF/statuses/165708049607172096</link><description>"@&lt;a class=" " href="http://twitter.com/ChineyyLynn"&gt;ChineyyLynn&lt;/a&gt;: LOL so then come box me chizzo and stop tuff chat over &lt;em&gt;twitter&lt;/em&gt;" funniest thing chizzo WILL do it. Ha. Take dat.</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/ShawtMonFTF/statuses/165708049607172096</guid><author>ShawtMonFTF@twitter.com (FuckTheFeds )</author><media:content type="image/jpg" height="48" width="48" url="http://a0.twimg.com/profile_images/1802873850/IMG00891-20110920-1637_normal.jpg"/><google:image_link>http://a0.twimg.com/profile_images/1802873850/IMG00891-20110920-1637_normal.jpg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item><item><title>RT @news2ch_visca: twitter&#x3067;&#x6709;&#x5409;&#x306b;&#x4ed8;&#x304d;&#x307e;&#x3068;&#x3063;&#x3066;&#x308b;&#x30df;&#x30b6;&#x30ea;&#x30fc;&#x5973;&#x304c;&#x75c5;&#x307f;&#x3059;&#x304e;&#x3066;&#x3066;&#x6016;&#x3059;&#x304e;&#x308b;&#x3068;&#x8a71;&#x984c;&#x306b; http://t.co/WVtN76DH via @news2ch_visca</title><link>http://twitter.com/kaaay0402/statuses/165708049535877120</link><description>RT @&lt;a class=" " href="http://twitter.com/news2ch_visca"&gt;news2ch_visca&lt;/a&gt;: twitter&#x3067;&#x6709;&#x5409;&#x306b;&#x4ed8;&#x304d;&#x307e;&#x3068;&#x3063;&#x3066;&#x308b;&#x30df;&#x30b6;&#x30ea;&#x30fc;&#x5973;&#x304c;&#x75c5;&#x307f;&#x3059;&#x304e;&#x3066;&#x3066;&#x6016;&#x3059;&#x304e;&#x308b;&#x3068;&#x8a71;&#x984c;&#x306b; &lt;a href="http://t.co/WVtN76DH"&gt;http://t.co/WVtN76DH&lt;/a&gt; via @&lt;a class=" " href="http://twitter.com/news2ch_visca"&gt;news2ch_visca&lt;/a&gt;</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/kaaay0402/statuses/165708049535877120</guid><author>kaaay0402@twitter.com (kaya@&#x5143;&#x6c17;&#x306a;&#x6839;&#x6697;)</author><media:content type="image/jpg" height="48" width="48" url="http://a2.twimg.com/profile_images/1760081995/image_normal.jpg"/><google:image_link>http://a2.twimg.com/profile_images/1760081995/image_normal.jpg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item><item><title>RT @_Madridistas_: ORGULLO MADRIDISTA http://t.co/FXSQKgeT</title><link>http://twitter.com/bea_m_s/statuses/165708049108041728</link><description>RT @&lt;a class=" " href="http://twitter.com/_Madridistas_"&gt;_Madridistas_&lt;/a&gt;: ORGULLO MADRIDISTA &lt;a href="http://t.co/FXSQKgeT"&gt;http://t.co/FXSQKgeT&lt;/a&gt;</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/bea_m_s/statuses/165708049108041728</guid><author>bea_m_s@twitter.com (BeAtRiZ)</author><media:content type="image/jpg" height="48" width="48" url="http://a2.twimg.com/profile_images/1788093348/image_normal.jpg"/><google:image_link>http://a2.twimg.com/profile_images/1788093348/image_normal.jpg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item><item><title>RT @BlameHarry: Facebook: I love sandwiches. Friends: Yeah nobody cares - Twitter: I love sandwiches. Followers: OMFG me too. White or whole grain?</title><link>http://twitter.com/ArmyForJustin/statuses/165708048969637889</link><description>RT @&lt;a class=" " href="http://twitter.com/BlameHarry"&gt;BlameHarry&lt;/a&gt;: Facebook: I love sandwiches. Friends: Yeah nobody cares - &lt;em&gt;Twitter&lt;/em&gt;: I love sandwiches. Followers: OMFG me too. White or whole grain?</description><pubDate>Sat, 04 Feb 2012 08:07:32 +0000</pubDate><guid>http://twitter.com/ArmyForJustin/statuses/165708048969637889</guid><author>ArmyForJustin@twitter.com (Verified Belieber )</author><media:content type="image/jpg" height="48" width="48" url="http://a1.twimg.com/profile_images/1802174032/396034_10150534318527834_512302833_8652706_148273060_n_normal.jpg"/><google:image_link>http://a1.twimg.com/profile_images/1802174032/396034_10150534318527834_512302833_8652706_148273060_n_normal.jpg</google:image_link><twitter:metadata><twitter:result_type>recent</twitter:result_type></twitter:metadata></item></channel></rss>

expand code box

All the code in one place

By popular request, here's a copy of all the above code in one place. It's a direct copy of the code used to display the results on this page:

<?PHP   if(!isset($_GET['q']) || !$q = $_GET['q']) $q = 'twitter';   $NUMITEMS   = 10;   $BLOGURL    = "http://search.twitter.com/search.rss?q=" . urlencode($q) . "&rpp=$NUMITEMS";   $TIMEFORMAT = "j F Y, g:ia";   $CACHEFILE  = "/tmp/" . md5($BLOGURL);   $CACHETIME  = 0.5; // hours # Original PHP code by Chirp Internet: www.chirp.com.au # Please acknowledge use of this code by including this header.   function expandLinks(&$input)   { // links matching the following regular expressions will be checked for redirects and expanded     $domains = array(       '[a-z0-9]{2,3}\.[a-z]{2}', '[a-z]{3,4}(url|ly)\.com'           );     if(preg_match_all("@http://((" . implode("|", $domains) . ")/[-a-z0-9]+)@i", $input, $matches)) {       $matches = array_unique($matches[1]);       foreach($matches as $shorturl) {         $command = "curl --head " . escapeshellarg($shorturl) . " | awk '($1 ~ /^Location/){print $2}'";         if($expandedurl = exec($command)) {           $input = str_replace("http://$shorturl", htmlspecialchars($expandedurl), $input);         }       }     }   }   function updateFeed()   {     global $BLOGURL, $CACHEFILE;     ini_set('user_agent', "TheArtOfWeb (http://{$_SERVER['HTTP_HOST']})");     if($feed_contents = file_get_contents($BLOGURL)) {       # expand shortened urls       expandLinks($feed_contents);       # write feed contents to cache file       $fp = fopen($CACHEFILE, 'w');       fwrite($fp, $feed_contents);       fclose($fp);     }   }   echo "<p>Read the latest tweets mentioning <b>$q</b> as of ";   if(file_exists($CACHEFILE)) {     echo date('g:ia', filemtime($CACHEFILE)) . ' local time';   } else {     echo 'right now';   }   echo ":</p>\n\n";   # download the feed iff cached version is missing   if(!file_exists($CACHEFILE)) updateFeed();   include "class.myrssparser.php";   $rss_parser = new myRSSParser($CACHEFILE);   # read feed data from cache file   $feeddata = $rss_parser->getRawOutput();   extract($feeddata['RSS']['CHANNEL'][0], EXTR_PREFIX_ALL, 'rss');   # display feed items   if($rss_ITEM) {     echo "<table border=\"0\" cellpadding=\"5\" cellspacing=\"0\">\n";     foreach($rss_ITEM as $itemdata) {       preg_match("/^(.*)@twitter\.com \((.*)\)$/", $itemdata['AUTHOR'], $regs);       list($foo, $author, $name) = $regs;       echo "<tr>\n";       echo "<td><a title=\"$name\" href=\"http://twitter.com/$author\" target=\"_blank\"><img src=\"{$itemdata['GOOGLE:IMAGE_LINK']}\" width=\"48\" height=\"48\" border=\"0\" alt=\"$author\"></a></td>\n";       echo "<td><p style=\"width: 600px; overflow: auto;\"><a href=\"http://twitter.com/$author\" target=\"_blank\">$author</a>: ";       echo str_replace('<a ', '<a rel="nofollow" target="_blank" ', stripslashes($itemdata['DESCRIPTION']));       echo "<br>\n";       echo "<small><a style=\"text-decoration: none; color: inherit;\" href=\"{$itemdata['GUID']}\" target=\"_blank\">";       echo date($TIMEFORMAT, strtotime($itemdata['PUBDATE']));       echo "</a></small>";       echo "</p></td>\n";       echo "</tr>\n";     }     echo "</table>\n\n";   } ?>

expand code box

And here's the code again to be included at the end of the page:

<?PHP // download the feed iff cached version is too old if((time() - filemtime($CACHEFILE)) > 3600 * $CACHETIME) { flush(); updateFeed(); } ?>

Related Articles

References

< PHP


User Comments and Notes

Edwin 21 June, 2010

I'm trying to implement your code on the website to follow tweets containing the keyword tourdekans. If I copy the parts of the code on the site into one file and load it it dispays an error 500. Is it possible to supply me the php file? Second question. How does that user agent work?

I've placed all the code together now at the end of the article. If you have trouble copying, try not using Firefox. For an explanation of the user agent, you should read this article.

Federico 23 September, 2010

Thanks for your code. Is really great!
Regards from Argentina!

dpoelen 6 December, 2010

Question: I might've missed it but where does $rss_ITEM come from?

The preceeding extract command extracts elements from a section of the $feeddata array into normal variables prefixed with rss_.

Dan 8 February, 2011

I worked through your tutorial and it worked like a charm. Thank you. Only question I have is that it seems to mash all hyperlinks together, removing the spaces between them. This includes hastags and bit.ly urls (i took out the expand links function).

It looks like there's a but in the RSS parser - when two links are separated only by white-space the white-space is being removed. I'll see if it can be patched...

karan 12 February, 2011

Thanks for the code. I'm not too familiar with caching yet but does this cache only the data from the rss feed. Do the remote images get cached to the server as well? So that they're not always loaded remotely.

Yes, only the data from the rss feed is cached - for $CACHETIME hours. Images (the avatar icons) are still sourced from Twitter. You could cache them locally if you wanted, but they will be always changing, and the largest is only around 10kb, so it's probably not worthwhile.

Send Feedback

Send Your Feedback (will not be published) (optional) CAPTCHA refresh <- copy the digits from the image into this box

[top]