PHP: Simple MyTweets Function


/ Published in: PHP

A simple PHP function for fetching tweets. Just provide your Twitter screen name and how many tweets you want and that is it. The function returns a simplified result set because you rarely need all the stuff that the Twitter API throws your way. If you need everything then just put FALSE as the last argument.


Copy this code and paste it in your HTML
  1. function myTweets($screenname, $count=5, $simple=TRUE) {
  2. $url = "http://twitter.com/statuses/user_timeline.json?screen_name={$screenname}&count={$count}&include_rts=1";
  3. $data = @file_get_contents($url);
  4. if ($http_response_header[0] != 'HTTP/1.0 200 OK'):
  5. return FALSE;
  6. endif;
  7. $data = json_decode($data);
  8. if ($simple == TRUE):
  9. $out = array();
  10. foreach ($data as $tweet):
  11. $o = new stdClass;
  12. $o->text = htmlentities($tweet->text, ENT_QUOTES, 'UTF-8', FALSE);
  13. $o->id = $tweet->id_str;
  14. $o->timestamp = strtotime($tweet->created_at);
  15. $o->url = "https://twitter.com/#!/{$screenname}/status/{$tweet->id_str}";
  16. $out[] = $o;
  17. endforeach;
  18. $data = $out;
  19. endif;
  20. return $data;
  21. }
  22.  
  23. $tweets = myTweets('sverrimo', 2);
  24. echo '<pre>', print_r($tweets);

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.