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.
- 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.
- Instantiate the class. No parameters can be passed here, to the constructor method.
- Use the
getXmlmethod to retrieve XML data for a given username either from the cache or from Twitter itself. - Use the
xmlToArraymethod to translate the XML into a PHP array. This method is separate fromgetXmlso 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…).