Snippets

Grab tweets from twitter feed

I use this to quickly grab my tweets and display them on my site. I am not the most mature programmer, for instance this could go into a class. I think this gets the job done quite nicely though. The only downfall is you must have your profile set to public.

<?php
     try {
          $count = 6;
            $tweet=json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/atrueresistance.json?count=".$count."" ));
            for ($i=1; $i < $count; $i++){
                //Assign feed to $feed
                $feed = $tweet[($i-1)]->text;
                //Find location of @ in feed
                $feed = str_pad($feed, 3, ' ', STR_PAD_LEFT);   //pad feed
                $startat = stripos($feed, '@');
                $numat = substr_count($feed, '@');
                $numhash = substr_count($feed, '#');
                $numhttp = substr_count($feed, 'http');
                $feed = preg_replace("/(http://)(.*?)/([w./&=?-,:;#_~%+]*)/", "<a href=""></a>", $feed);
                $feed = preg_replace("(@([a-zA-Z0-9_]+))", "<a href="http://www.twitter.com/\1"></a>", $feed);
                $feed = preg_replace('/(^|s)#(w+)/', '1<a href="http://search.twitter.com/search?q=%232">#2</a>', $feed);
                echo "<div class='tweet'>".$feed.  "<div class='tweet_date'>". date("M - j",strtotime($tweet[($i-1)]->created_at))."
                        </div></div>";
                }
      } catch (Exception $e) {
          echo "Twitter feed is currently down, check back later.";
      }

?>

Share this snippet

 
  • Andy

    I found a class here on this site
    http://www.thetutlage.com/post=TUT177

    Seems promising to me..