Use PHP to cache and display your tweeted links
Posted August 21, 2009 by Brian Cray
Reading time: About 1 minute
This PHP tutorial fetches your last 10 tweets containing links using the Twitter Search API, then displays them in an unordered list (<ul>). It requires PHP 5.2.0 or above to use PHP‘s built-in JSON functions.
As an added benefit it stores the fetched tweets in a local cache to keep from running into the API limit and links URLs and Twitter usernames so users can click them. Pretty nifty, eh?
Let’s get to the code.
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 | // the function function get_twitter() { $tweets = 10; $username = 'briancray'; $url = 'http://search.twitter.com/search.json?q=' . urlencode('from:' . $username . ' filter:links') . '&rpp=' . $tweets; $cache = dirname(__FILE__) . '/caches/twitter'; if(filemtime($cache) < (time() - 60)) { mkdir(dirname(__FILE__) . '/caches', 0777); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); curl_setopt($ch, CURLOPT_TIMEOUT, 5); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']); $data = curl_exec($ch); curl_close($ch); $cachefile = fopen($cache, 'wb'); fwrite($cachefile, $data); fclose($cachefile); } else { $data = file_get_contents($cache); } $json = json_decode($data); $html = '<ul>'; foreach($json->results as $item) { $item->text = preg_replace('/(https?:\/\/[a-zA-Z\-0-9\.\/]+)[^a-zA-Z\-0-9\.\/]?/', '<a href="\\1" target="_blank">\\1</a>', $item->text); $item->text = preg_replace('/@(\w+)\b/', '@<a href="http://twitter.com/\\1" target="_blank">\\1</a>', $item->text); $html .= '<li>' . $item->text . '</li>'; } $html .= '</ul>'; return $html; } // to display them: echo get_twitter(); |
1 Article references from other blogs
1082
9 Article comments
Show/add comments