Advertisement
olie480

Twitter Parsing

Jun 12th, 2013
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.93 KB | None | 0 0
  1. /// For caching in a database; Use as a CRON
  2.  
  3. function getTweets($user, $num = 3) {
  4.     //first, get the user's timeline
  5.     $ch = curl_init();
  6.     curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/$user.json?count=$num");
  7.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  8.     $json = curl_exec($ch);
  9.     curl_close($ch);
  10.  
  11.     if ($json === false) { return false; } //abort on error
  12.  
  13.     //second, convert the resulting json into PHP
  14.     $result = json_decode($json);
  15.  
  16.     //third, build up the html output
  17.     $s = '';
  18.     foreach ($result as $item) {
  19.         //handle any special characters
  20.         $text = htmlentities($item->text, ENT_QUOTES, 'utf-8');
  21.  
  22.         //build the metadata part
  23.         $meta = date('g:ia M jS', strtotime($item->created_at)) . ' from ' . $item->source;
  24.  
  25.         //parse the tweet text into html
  26.         $text = preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1">$1</a>', $text);
  27.         $text = preg_replace('/@(\w+)/', '<a href="http://twitter.com/$1">@$1</a>', $text);
  28.         $text = preg_replace('/\s#(\w+)/', ' <a href="http://search.twitter.com/search?q=%23$1">#$1</a>', $text);
  29.  
  30.         //assemble everything
  31.         $s .= '<p class="tweet">' . $text . "<br />\n" . '<span class="tweet-meta">' . $meta . "</span></p>\n";
  32.     }
  33.  
  34.     return $s;
  35. }
  36.  
  37.  
  38. // Regex for replacing links,users, and hashtags
  39.  
  40. $status = $cb->statuses_userTimeline($params); // Using codebird
  41. foreach( $status as $stat):
  42. if($stat->text){    
  43.   $text = $stat->text;
  44.   // Twitter Links
  45.   $text = preg_replace('@(https?://([-\w\.]+)+(/([\w/_\.]*(\?\S+)?(#\S+)?)?)?)@', '<a href="$1">$1</a>', $text);
  46.   // Twitter Users
  47.   $text = preg_replace('/@(\w+)/', '<a href="http://twitter.com/$1">@$1</a>', $text);
  48.   // Twitter Hashtags
  49.   $text = preg_replace('/\s+#(\w+)/', ' <a href="http://search.twitter.com/search?q=%23$1">#$1</a>', $text);
  50.  
  51.   echo $text;
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement