Written by Brian Cray on August 21st, 2009
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.
// 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();