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;
}

3 comments:

  1. This will return the tweets from the twitter, and replace the @username by their links, and also (http:...) replace this by url using regular expression.....

    ReplyDelete
  2. @jahir is it works on core php with out any framework? because i got a fatal error on $ch = curl_init(); function.

    Any suggestions to get the correct output

    ReplyDelete
  3. @ram this is core php only... you check your php.ini (phpinfo()).....you need to enable curl option in your php.ini file.

    ReplyDelete