Tuesday 10 January 2012

Parsing Twitter Username

      echo getTweets("jagir", 1);


function getTweets($user, $num = 3) {
//first, get the user's timeline
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$user.json?count=$num");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$json = curl_exec($ch);
curl_close($ch);

if ($json === false) { return false; } //abort on error

//second, convert the resulting json into PHP
$result = json_decode($json);

//third, build up the html output
$s = '';
foreach ($result as $item) {
//handle any special characters
$text = htmlentities($item->text, ENT_QUOTES, 'utf-8');

//build the metadata part
$meta = date('g:ia M jS', strtotime($item->created_at)) . ' from ' . $item->source;

//parse the tweet text into html
$text = preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1">$1</a>', $text);
$text = preg_replace('/@(\w+)/', '<a href="http://twitter.com/$1">@$1</a>', $text);
$text = preg_replace('/\s#(\w+)/', ' <a href="http://search.twitter.com/search?q=%23$1">#$1</a>', $text);

//assemble everything
$s .= '<p class="tweet">' . $text . "<br />\n" . '<span class="tweet-meta">' . $meta . "</span></p>\n";
}

return $s;
}