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();

About the author

Photo of Brian Cray

Brian Cray is a Columbus, Ohio-based web entrepreneur & consultant. View some of Brian’s work in his portfolio and learn how to make kick ass websites by reading his blog.

9 Article comments

Show/add comments

1 Article references from other blogs

Show all references

1082
Previous:
Next: