PHP: Displaying Twitter Search Results in HTMLHere'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 TwitterThe 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 formatIn 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 resultsHere 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 12:45am local time:
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 FeedHere 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?q=twitter&rpp=10&since_id=10644888860</twitter:refresh_url>
<pubDate>Wed, 17 Mar 2010 23:45:08 +0000</pubDate>
<openSearch:itemsPerPage>10</openSearch:itemsPerPage>
<item>
<title>*Mee maatandu para axaar um planuu de fundo proo meu kiriido: #TWITTER :D</title>
<link>http://twitter.com/AlineTD2/statuses/10644888860</link>
<description>*Mee maatandu para axaar um planuu de fundo proo meu kiriido: <a href="http://search.twitter.com/search?q=%23TWITTER">#<b>TWITTER</b></a> :D</description>
<pubDate>Wed, 17 Mar 2010 23:45:08 +0000</pubDate>
<guid>http://twitter.com/AlineTD2/statuses/10644888860</guid>
<author>AlineTD2@twitter.com (Aliine )</author>
<media:content url="http://a3.twimg.com/profile_images/759062137/100_0681_normal.jpg" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a3.twimg.com/profile_images/759062137/100_0681_normal.jpg</google:image_link>
</item>
<item>
<title>Nette Studienidee: Wie wirkt sich #twitter auf die #Feed-Nutzung aus? Bei mir ein TOTALER Wechsel zum zwitschern! Wie siehts bei euch aus?</title>
<link>http://twitter.com/pixelmetrie/statuses/10644888664</link>
<description>Nette Studienidee: Wie wirkt sich <a href="http://search.twitter.com/search?q=%23twitter">#<b>twitter</b></a> auf die #Feed-Nutzung aus? Bei mir ein TOTALER Wechsel zum zwitschern! Wie siehts bei euch aus?</description>
<pubDate>Wed, 17 Mar 2010 23:45:07 +0000</pubDate>
<guid>http://twitter.com/pixelmetrie/statuses/10644888664</guid>
<author>pixelmetrie@twitter.com (Matthias König)</author>
<media:content url="http://a3.twimg.com/profile_images/546161125/1-e138d101f71406cf_normal.jpg" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a3.twimg.com/profile_images/546161125/1-e138d101f71406cf_normal.jpg</google:image_link>
</item>
<item>
<title>RT @BrendaClayson: U choose who U associate with & spend time with (in life & on twitter). Don't like what you see? Do something about it.:)</title>
<link>http://twitter.com/LeeCaraher/statuses/10644888565</link>
<description>RT <a href="http://twitter.com/BrendaClayson">@BrendaClayson</a>: U choose who U associate with &amp; spend time with (in life &amp; on <b>twitter</b>). Don&apos;t like what you see? Do something about it.:)</description>
<pubDate>Wed, 17 Mar 2010 23:45:07 +0000</pubDate>
<guid>http://twitter.com/LeeCaraher/statuses/10644888565</guid>
<author>LeeCaraher@twitter.com (LeeCaraher)</author>
<media:content url="http://a3.twimg.com/profile_images/67262409/LEE_4_x_5_normal.jpg" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a3.twimg.com/profile_images/67262409/LEE_4_x_5_normal.jpg</google:image_link>
</item>
<item>
<title>RT @TheProTips: If your Twitter profile is private and you send an @ reply to someone, they won't see it unless they're following you.</title>
<link>http://twitter.com/SwaggCertified/statuses/10644888520</link>
<description>RT <a href="http://twitter.com/TheProTips">@TheProTips</a>: If your <b>Twitter</b> profile is private and you send an @ reply to someone, they won&apos;t see it unless they&apos;re following you.</description>
<pubDate>Wed, 17 Mar 2010 23:45:07 +0000</pubDate>
<guid>http://twitter.com/SwaggCertified/statuses/10644888520</guid>
<author>SwaggCertified@twitter.com (Swagg Certified)</author>
<media:content url="http://a3.twimg.com/profile_images/730664227/dailybooth-2_normal.jpg" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a3.twimg.com/profile_images/730664227/dailybooth-2_normal.jpg</google:image_link>
</item>
<item>
<title>RT @Mileycyruschile: RT: Si amas Twitter.</title>
<link>http://twitter.com/herewegomaureen/statuses/10644888430</link>
<description>RT <a href="http://twitter.com/Mileycyruschile">@Mileycyruschile</a>: RT: Si amas <b>Twitter</b>.</description>
<pubDate>Wed, 17 Mar 2010 23:45:07 +0000</pubDate>
<guid>http://twitter.com/herewegomaureen/statuses/10644888430</guid>
<author>herewegomaureen@twitter.com (Maureen Torres)</author>
<media:content url="http://a3.twimg.com/profile_images/759096213/IMG0157A_normal.jpg" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a3.twimg.com/profile_images/759096213/IMG0157A_normal.jpg</google:image_link>
</item>
<item>
<title>Jus made dis twitter idk fah wat?mi sista wanted me 2!lol!but wats gud Twitter!lol!</title>
<link>http://twitter.com/mizztay15/statuses/10644888408</link>
<description>Jus made dis <b>twitter</b> idk fah wat?mi sista wanted me 2!lol!but wats gud <b>Twitter</b>!lol!</description>
<pubDate>Wed, 17 Mar 2010 23:45:07 +0000</pubDate>
<guid>http://twitter.com/mizztay15/statuses/10644888408</guid>
<author>mizztay15@twitter.com (Tashia)</author>
<media:content url="http://a3.twimg.com/profile_images/759044005/m_228fb0fb0a3a484abc98e49343b9fb7d_normal.jpg" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a3.twimg.com/profile_images/759044005/m_228fb0fb0a3a484abc98e49343b9fb7d_normal.jpg</google:image_link>
</item>
<item>
<title>ru_go (「・ω・)「がおー
http://twitter.com/ru_go/status/10625576548</title>
<link>http://twitter.com/gaoh_bot/statuses/10644888343</link>
<description>ru_go (「・ω・)「がおー
<a href="http://twitter.com/ru_go/status/10625576548">http://<b>twitter</b>.com/ru_go/status/10625576548</a></description>
<pubDate>Wed, 17 Mar 2010 23:45:07 +0000</pubDate>
<guid>http://twitter.com/gaoh_bot/statuses/10644888343</guid>
<author>gaoh_bot@twitter.com ((「・ω・)「がおー)</author>
<media:content url="http://a3.twimg.com/profile_images/324758753/gaoh_normal.png" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a3.twimg.com/profile_images/324758753/gaoh_normal.png</google:image_link>
</item>
<item>
<title>On Twitter: BradBurton: RT @realgoodwriting: @bradburton OMG, I was 19 - she's 66 though http://businessnetworking.ws/2010/03/bradburton-rt-realgoodwriting-bradburton-omg-i-was-19-shes-66-though/</title>
<link>http://twitter.com/ImAfterdotcom/statuses/10644888296</link>
<description>On <b>Twitter</b>: BradBurton: RT <a href="http://twitter.com/realgoodwriting">@realgoodwriting</a>: <a href="http://twitter.com/bradburton">@bradburton</a> OMG, I was 19 - she&apos;s 66 though <a href="http://businessnetworking.ws/2010/03/bradburton-rt-realgoodwriting-bradburton-omg-i-was-19-shes-66-though/">http://businessnetworking.ws/2010/03/bradburton-rt-realgoodwriting-bradburton-omg-i-was-19-shes-66-though/</a></description>
<pubDate>Wed, 17 Mar 2010 23:45:07 +0000</pubDate>
<guid>http://twitter.com/ImAfterdotcom/statuses/10644888296</guid>
<author>ImAfterdotcom@twitter.com (Danjal Es)</author>
<media:content url="http://a3.twimg.com/profile_images/324460375/imafterlogo2a_normal.jpg" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a3.twimg.com/profile_images/324460375/imafterlogo2a_normal.jpg</google:image_link>
</item>
<item>
<title>Frédéric Lefebvre caricaturé sur Twitter http://www.sabeb.com/a-la-une-2010/frederic-lefebvre-caricature-sur-twitter-53359.html</title>
<link>http://twitter.com/sabebcom/statuses/10644888203</link>
<description>Frédéric Lefebvre caricaturé sur <b>Twitter</b> <a href="http://www.sabeb.com/a-la-une-2010/frederic-lefebvre-caricature-sur-twitter-53359.html">http://www.sabeb.com/a-la-une-2010/frederic-lefebvre-caricature-sur-twitter-53359.html</a></description>
<pubDate>Wed, 17 Mar 2010 23:45:07 +0000</pubDate>
<guid>http://twitter.com/sabebcom/statuses/10644888203</guid>
<author>sabebcom@twitter.com (sabeb)</author>
<media:content url="http://a1.twimg.com/profile_images/675028738/48280_normal.jpg" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a1.twimg.com/profile_images/675028738/48280_normal.jpg</google:image_link>
</item>
<item>
<title>RT @WhoIsPolo: I"m sick of twitter... Dis shit lame... -- #hereUgo , you better keep ya ass logged in !</title>
<link>http://twitter.com/sheeduhh/statuses/10644888049</link>
<description>RT <a href="http://twitter.com/WhoIsPolo">@WhoIsPolo</a>: I&quot;m sick of <b>twitter</b>... Dis shit lame... -- <a href="http://search.twitter.com/search?q=%23hereUgo">#hereUgo</a> , you better keep ya ass logged in !</description>
<pubDate>Wed, 17 Mar 2010 23:45:06 +0000</pubDate>
<guid>http://twitter.com/sheeduhh/statuses/10644888049</guid>
<author>sheeduhh@twitter.com (rashida hewitt)</author>
<media:content url="http://a1.twimg.com/profile_images/751624410/70719283_normal.jpg" type="image/jpg" width="48" height="48"/>
<google:image_link>http://a1.twimg.com/profile_images/751624410/70719283_normal.jpg</google:image_link>
</item>
</channel>
</rss>
Related Articles
References |
||||||||||||||||||||
|
© Copyright 2010 Chirp Internet
- Page Last Modified: 22 November 2009
|
||||||||||||||||||||