Building a Twitter PHP Class.

When I sat down to design and develop the new RyanLahay.com, I knew I wanted to have a nice little Twitter feed at the bottom. What I didn’t know was that I would be writing a Twitter class from scratch.

It seems simple enough. A little Twitter feed at the bottom of your homepage. It is… now.

I’m an advocate of efficiency – in not recreating the wheel. With that mindset, I sent myself out on the task of finding a quick, simple pre-written Twitter script that I could use to plug into the bottom of this very page you are reading. All I wanted was a quick script without a whole bunch of ‘extras’ that would just pull in a select number of tweets, and list them in ul > li format.

This brings me to character flaw #87. I have little patience. I looked on various sites for a maximum of 30 minutes before I got frustrated and decided to just quickly build my own. So, today, I present to you the fruits of my labor – a Twitter feed class. It isn’t perfect, but hopefully it will save some other developer an evening of their time. Feel free to comment below and post any bugs or revisions!

Quick overview of features

  • Reads a twitter account’s RSS feed
  • Parses a requested amount of tweets (the maximum of which is limited by the amount of tweets in the feed)
  • Option to filter out tweets that contain characters you might not want to show on your site. (ie: I did not want my personal site to show “replies”, so I filter out tweets that start with “@”
  • Option to assign a style and id to the ul
  • Option to assign a style to li elements
  • Option to assign a style to first, and last li elements
  • Option to assign a style to anchor elements
  • Option to prepend, and append tweet text
  • Autolinks URL’s in tweets

Current Limitations

  • Only shows tweets from one feed/account at a time
  • Is not currently caching

Usage

// basic setup and display
include "twitter.class.php";
$feed=new TwitterFeed();
$feed->feedURL="http://twitter.com/statuses/user_timeline/23829176.rss";
$feed->username="rlahay";
echo $feed->listTweets();

// alternatively, you can do something a bit more fancy...
// here is the excerpt from the setup for this page
include"twitter.class.php";
$feed=new TwitterFeed();
$feed->feedURL="http://twitter.com/statuses/user_timeline/23829176.rss";
$feed->username="rlahay";
$feed->posts=4;
$feed->ulID="twitterFeed";
$feed->prepend="<div class=\"tweet\">";
$feed->append="</div>";
$feed->lastLiClass="last";
echo $feed->listTweets();

You may download the class here, or at the top of the page.

First Published On: December 1, 2009

Leave a Reply

Recent Articles