I am a web designer and client-side developer living in Brooklyn, NY and working at HUGE.

PHP Twitter Feed Class

October 20, 2008 I'm done here, let's go home …

When I was building this site, I wanted to include a Twitter feed. I didn't want to bother with signing up for their API or anything and their "badges" didn't cut it - I didn't want to rely on JavaScript to show the feed. So, I decided to write a PHP class to grab that data. And now I'm sharing it!

The class I created, aptly named "twitterFeed" is dead easy to implement, but has a few requirements:

  • PHP cURL Library allows you to grab remote files from your web server. In this case, XML Twitter feeds.
  • PEAR Cache is required to cache XML files you grab from Twitter. This means that the script will only download new XML if the cache has been sitting on your server for longer than you set the cache timeout.
  • And finally, PHP SimpleXML is used to parse the XML.

Luckily, my web host had all three of these features installed.

If your web host has these features, you're in luck. If not, ask them politely if they'll install them!

Using twitterFeed

The class twitterFeed essentially acts as a retrieval and formatting mechanism. It pulls down an XML file from Twitter, parses it, formats the data, and returns a neatly organized array of data.

To prepare for the use of twitterFeed, you need to create a directory to store the cached file(s). This defaults to $_SERVER['DOCUMENT_ROOT'].'/cache' so the easiest way is to create a folder called "cache" in your web root ("public_html" or whatever it is). You can modify the location of the cache using the setCacheDir method.

Once your cache directory is created, the basic use of twitterFeed couldn't be simpler…

<?php

if (include('class.twitterFeed.php'))
{
    $twitterFeed = new twitterFeed;
    $twitterFeed->getXml('pgoneill');
    $twitterData = $twitterFeed->xmlToArray(5);
}

?>
			

Let's go through that piece by piece.

  1. Include the class itself. Here, I've wrapped the include in an "if" statement, so this block will be ignored if the file is not found.
  2. Instantiate the class. No parameters can be passed here, to the constructor method.
  3. Use the getXml method to retrieve XML data for a given username either from the cache or from Twitter itself.
  4. Use the xmlToArray method to translate the XML into a PHP array. This method is separate from getXml so if you want you can simply use the raw XML for your own purposes.

Then, you just have to use PHP to output that data in a way that makes sense. Here's how I output it on this site…

<?php

    if ($twitterData)
    {
        echo "\t\t\t\t\t".'<ol id="twitter">'."\n";

        foreach ($twitterData['tweets'] as $tweet)
        {
            echo "\t\t\t\t\t\t".'<li>'."\n";
            echo "\t\t\t\t\t\t\t".'<p>'.$tweet['text'].'</p>'."\n";
            echo "\t\t\t\t\t\t\t".'<p class="date"><a href="'.$tweet['link'].'">'.$tweet['time_ago'].'</a></p>'."\n";
            echo "\t\t\t\t\t\t".'</li>'."\n";
        }

        echo "\t\t\t\t\t".'</ol>'."\n";
        echo "\t\t\t\t\t".'<div id="twitter-user" class="clearfix">'."\n";
        echo "\t\t\t\t\t\t".'<img src="' . $twitterData['user']['image_url_small'] . '" alt="Profile Image" />'."\n";
        echo "\t\t\t\t\t\t".'<p>Why not <a href="http://twitter.com/' . $twitterData['user']['screen_name'] . '">';
        echo 'become my '.show_ordinal($twitterData['user']['followers']+1).' follower</a>?</p>'."\n";
        echo "\t\t\t\t\t\t".'<a class="twitter" href="http://twitter.com/'.$twitterData['user']['screen_name'].'">Updates via Twitter</a>'."\n";
        echo "\t\t\t\t\t".'</div>'."\n";
    }
    else
    {
        echo "\t\t\t\t\t".'<p>There was some kind of problem contacting the Twitter service.  Maybe later.</p>'."\r\n";
    }

?>
			

That's all there is to it! However, you can do a fair amount of customizing the way twitterFeed works using a number of built-in methods.

twitterFeed Methods

setCacheTime
This method takes one parameter: an integer equal to the number of minutes you would like your cache to last. Example, if you use $twitterFeed->setCacheTime(60);, your cached XML will last for an hour.
setCacheDir
This method takes one parameter: a string with a directory path to the directory you intend to use for your cache. Remember, the script defaults to a directory named "cache" in your web root, so you only need to use this method if you want to use a different directory!
setRel
Use this method to set a "rel" attribute on all links inside your tweets. The value of this defaults to 'nofollow' so all links inside tweets will have rel="nofollow" by default. If you want to disable this, you could use $twitterFeed->setRel('');.
getXml
As described earlier, this method retrieves XML data based on a Twitter username. For me, it's $twitterFeed->getXml('pgoneill');. This method will fail if your server does not meet all the requirements listed earlier.
xmlToArray
Also described earlier, this method converts a Twitter XML file into a nicely formatted array (it doesn't just use SimpleXML if that's what you're wondering - it's more than that).

If you're curious to see what the array looks like, I have an example up. It shows the data returned using the first code block above.

One Last Thing

If you just tweeted something and you really don't want to wait for the cache to reset, you can add a parameter called reset_cache to the URL of the page using twitterFeed. For example, to reset the cache on my homepage, you'd visit http://www.patrick-oneill.com/?reset_cache. Just stick ?reset_cache on the end of the URL and the cache will be cleared! Magic!

Download

Download class.twitterFeed.phps by either the "right-click, save as" method or you can view it as source code (if MediaTemple ever answers my support ticket…).

Other Articles

  1. PHP Twitter Feed Class

    October 20, 2008

    When I was building this site, I wanted to include a Twitter feed. I didn't want to bother with signing up for their API or anything and their "badges" didn't cut it - I didn't want to rely on JavaScript to show the feed. So, I decided to write a PHP class to grab that data. And now I'm sharing it!

    Continue reading …
  2. Facile Forms Framework

    January 29, 2008

    I've marked up quite a few HTML forms in my day. On complex sites, the problem often becomes maintaining a consistent presentation of form elements across a variety of pages, columns widths, and so on.

    Continue reading …
  1. Using CSS to Target Multiple Internet Explorer Versions

    January 10, 2007

    I thought I'd share my method of targeting CSS fixes for multiple versions of Internet Explorer in light of IE7's recent release. It's a two-pronged approach combining Microsoft's proprietary Conditional Comments and various CSS filters.

    Continue reading …
  2. Another PHP Contact Form Script

    December 14, 2006

    Just what the world needs. Another PHP-based contact form script! I know, I know. There's a million of these out there. But this is the one I use on my web design and development portfolio.

    Continue reading …
  3. Movin' On Up

    January 8, 2006

    After 16 months at Oklahoma State University, I'm leaving to pursue new employment. As of January 17th, I'll no longer be an OSU employee and will begin working full-time for my father's company, O'Neill Marketing Communications. Part of my work week will be sub-contracted to Nomadics, Inc. ICx Technologies where I've been hired to complement their marketing team on a part-time basis.

    Continue reading …