<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" version="2.0">

<channel>
	<title>Carron Media</title>
	
	<link>http://www.carronmedia.com</link>
	<description>Web Design &amp; Development</description>
	<lastBuildDate>Wed, 04 Aug 2010 19:25:52 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/CarronMedia" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="carronmedia" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Display your latest Twitter update with jQuery, part 2</title>
		<link>http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery-part-2/</link>
		<comments>http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery-part-2/#comments</comments>
		<pubDate>Sun, 09 May 2010 11:36:42 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Twitter]]></category>
		<category><![CDATA[XHTML]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=413</guid>
		<description><![CDATA[Back in July of last year, we published the article Display your latest Twitter update with jQuery to show you how simple it was to display your latest Tweets on your website using jQuery. Since that article was published, Twitter have made some changes to their core API which affects how the script in this [...]]]></description>
			<content:encoded><![CDATA[<p>Back in July of last year, we published the article <a href="http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/">Display your latest Twitter update with jQuery</a> to show you how simple it was to display your latest Tweets on your website using jQuery. Since that article was published, Twitter have made some changes to their core API which affects how the script in this article works. Before carrying on, if you haven’t already, I recommend that you read the <a href="http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/">original article</a> first so that the following makes sense.</p>
<p>Everything was working nice and smoothly until Twitter changed the way users can retweet from the main Twitter website. Not that this was a bad thing, the new(ish) functionality was a great addition to an already great service. Before the changes, users manually typed &#8216;RT&#8217; at the beginning of their tweet to signify that they have retweeted it from another user. Now days, you simply click a button which will take care of it for you.</p>
<p>But, as <a href="http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/#comment-1097">Kerem</a> pointed out in the comments of the original article, our code does not display these new retweets. Instead, it just displays an empty space where your latest tweet should be sitting pride of place. In nearly all circumstances, I would imagine that this is not the desired effect, especially as the retweet functionality is used a lot more these thanks to the new functionality.</p>
<p>As a result, I have got back to the drawing board to investigate how we can get around this problem and improve the current script. If you wish, you can <a title="Download source files" href="http://www.carronmedia.com/publicfiles/twitter2.zip">download the sources files</a> before continuing on.</p>
<p><span id="more-413"></span></p>
<h4>The Cause of the Issue</h4>
<p>The find out why this was happening, we started looking in the <a href="http://apiwiki.twitter.com">Twitter API Wiki</a>. The <a href="http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-user_timeline">statuses user_timeline</a> page revealed that the <code>user_timeline</code> API call does not support the new retweets when the data has been requested in the JSON or XML formats:</p>
<blockquote><p>&ldquo;Note: For backwards compatibility reasons, retweets are stripped out of the user_timeline when calling in XML or JSON (they appear with &#8216;RT&#8217; in RSS and Atom).&rdquo;</p></blockquote>
<p>The obviously impacts the code we wrote in the <a href="http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/">original article</a> as we used the JSON format for our returned data. Unfortunately, they don&#8217;t expand as to why the no longer support these formats, so we are just going to have to take their word for it.</p>
<h4>The Solution</h4>
<p>As it turns out, the solution to this issue is relatively simple, but implementing that solution is slightly trickier as it will require some server-side code (of which I will go into later).</p>
<p>As per the Twitter API, the <code>user_timeline</code> API call still supports the RSS and Atom formats. Therefore we can simply change the API request URL to return our data as an RSS feed. If the latest tweet is a retweet now, the text is simply prefixed with an ‘RT’. This is much more useful that a blank tweet, as I’m sure you will agree.</p>
<p>This method does have a few drawbacks though. In our code, we use the jQuery <code>.getScript()</code> method to send our API call to Twitter and return our tweet. This is fine for the JSON format (it’s JavaScript, which can be opened with .getScript), but is not valid for the XML of the RSS feed.</p>
<p>Therefore, we are going to use jQuery’s <code>.get()</code> method instead. However, it not a straight swap because for security reasons, this method will (quite sensibly) only let you request local files with this function and our request is going directly to the Twitter API (i.e, not local).</p>
<h4>Cache the tweet locally with PHP</h4>
<p>There is a really simply solution to this problem though, using a <a href="http://paulofierro.com/archives/459/">PHP proxy script</a>, we can load the data locally.</p>
<p>This file will sit locally on you server, and instead of calling the Twitter API directly, we will call it in the query string of this proxy.php file.  This means that our new request URL will look as follows:</p>
<pre class="brush: jscript;">proxy.php?url=http://twitter.com/statuses/user_timeline/' + username + '.rss?count=1</pre>
<p>Here is the source code of the proxy.php script (the file is included in the download at the bottom of the page). Save the file to a web accessible folder on your server:</p>
<pre class="brush: php;">&lt;?php
// PHP Proxy
// Loads a XML from any location. Used with Flash/Flex apps to bypass security restrictions
// Author: Paulo Fierro
// January 29, 2006

$session = curl_init($_GET['url']);
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
$xml = curl_exec($session);
header(&quot;Content-Type: text/xml&quot;);
echo $xml
curl_close($session);
?&gt;
</pre>
<p>Basically, this script uses the <a href="http://www.php.net/manual/en/intro.curl.php">PHP cURL Extension</a> to open the file sent to it in the query string. It then strips away any additional information, such as the file headers, to leave the raw data (the XML of the RSS feed in our case). Finally, it changes the output header to XML and the returns the raw data.</p>
<h4>The new jQuery</h4>
<p>As we have changed the format of our data, will we need to change the way jQuery parses that data.  In the <a href="http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/">original article</a>, we basically took Twitters own code and tweaked it slightly. This time around, it’s going to be easier and quicker just to rewrite it.</p>
<p>The new JavaScript file (named <code>twitter2.js</code>) is included in the download for this article.</p>
<p>Here is the <code>twitter2.js</code> file in full. I will run through the code in chunks to give you an understanding of what is going on.</p>
<p><strong>UPDATE:</strong> <a href="#comment-1459">Ed Knittel</a> quite correctly points out in the comments that the date format in the RSS results differs to that of the JSON results. Therefore, I have updated the code below to reflect this format difference.</p>
<pre class="brush: jscript;">function relative_time(time_value) {
    var newtime = time_value(',','');
    var values = newtime.split(&quot; &quot;);
    time_value = values[2] + &quot; &quot; + values[1] + &quot;, &quot; + values[3] + &quot; &quot; + values[4];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length &gt; 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    if (delta &lt; 60) {
        return 'less than a minute ago';
    } else if(delta &lt; 120) {
        return 'about a minute ago';
    } else if(delta &lt; (60*60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if(delta &lt; (120*60)) {
        return 'about an hour ago';
    } else if(delta &lt; (24*60*60)) {
        return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if(delta &lt; (48*60*60)) {
        return '1 day ago';
    } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
    }
}

$(function() {

    var username = '&lt;yourtwitterusername&gt;';

    $.get('&lt;path-to-file&gt;/proxy.php?url=http://twitter.com/statuses/user_timeline/' + username + '.rss?count=1', function(tweets) {
        $(tweets).find('item').each(function() {
            var tweet = $(this);
            var pattern = new RegExp(&quot;^&quot;+username+&quot;: &quot;,&quot;g&quot;);
            var status = tweet.find('description').text().replace(/((https?|s?ftp|ssh)\:\/\/[^&quot;\s\&lt;\&gt;]*[^.,;'&quot;&gt;\:\s\&lt;\&gt;\)\]\!])/g, function(url) {
                return '&lt;a href=&quot;'+url+'&quot;&gt;'+url+'&lt;/a&gt;';
            }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
                return  reply.charAt(0)+'&lt;a href=&quot;http://twitter.com/'+reply.substring(1)+'&quot;&gt;'+reply.substring(1)+'&lt;/a&gt;';
            }).replace(pattern,'');
            var tweetDate = relative_time(tweet.find('pubDate').text());
            $('.loading').fadeOut(750, function() {
                $('#latest_tweet').append($('&lt;p&gt;&amp;ldquo;'+status+'&amp;rdquo; &lt;small&gt;- &lt;span&gt;'+tweetDate+'&lt;/span&gt;&lt;/small&gt;&lt;/p&gt;').hide().fadeIn(750));
            });
        });
    });
});
</pre>
<p>First of all, we define a function that turns the time and date of the tweet into something that is more understandable to humans. This is identical to the original, so I won’t go into detail again.</p>
<pre class="brush: jscript;">
$(function() {

    var username = '&lt;yourtwitterusername&gt;';
</pre>
<p>Here we create the standard jQuery on DOM ready function and set a variable called <code>username</code> to store your Twitter username:</p>
<pre class="brush: jscript;">
$.get('&lt;path-to-file&gt;/proxy.php?url=http://twitter.com/statuses/user_timeline/' + username + '.rss?count=1', function(tweets) {
</pre>
<p>Next we request the RSS data from Twitter using jQuery’s <code>.get()</code> method. This is where we load your latest tweet via the proxy.php file (make sure you include the correct file path to the proxy.php file if it is in a different directory to this JavaScript file). If you would like to load more than one tweet, change the final option in the URL (e.g. enter <code>count=3</code> at the end of the query string if you would like to return three tweets). The data returned from the Twitter API in then stored in an object called <code>tweets</code> which can the be called in the callback function.</p>
<pre class="brush: jscript;">
$(tweets).find('item').each(function() {
    var tweet = $(this);
    var pattern = new RegExp(&quot;^&quot;+username+&quot;: &quot;,&quot;g&quot;);
</pre>
<p>In the next block of code, we need to search through the XML to find the text and time of each tweet. We use the <code>.find()</code> method to search through the XML and locate each XML element called ‘item’. We then loop through each of the discovered elements. We set a variable called <code>tweet</code> which caches the currently selected element in the loop.</p>
<p>The next step is to create a new RegExp object. By default, you may have noticed that the Twitter API not only prefixes the tweet with RT if necessary, it also prefixes every tweet with your Twitter username. The regular expression here simply matches your Twitter username so we can remove it from the tweet later on.</p>
<pre class="brush: jscript;">
var status = tweet.find('description').text().replace(/((https?|s?ftp|ssh)\:\/\/[^&quot;\s\&lt;\&gt;]*[^.,;'&quot;&gt;\:\s\&lt;\&gt;\)\]\!])/g, function(url) {
    return '&lt;a href=&quot;'+url+'&quot;&gt;'+url+'&lt;/a&gt;';
}).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
    return  reply.charAt(0)+'&lt;a href=&quot;http://twitter.com/'+reply.substring(1)+'&quot;&gt;'+reply.substring(1)+'&lt;/a&gt;';
}).replace(pattern,'');
</pre>
<p>Now, at first glance, this chunk of code may look a bit confusing, but don’t let that put you off. We start by extracting the actual text of the tweet from the XML data, again using jQuery&#8217;s <code>.find()</code> method. We then pass this text through three regular expressions. The first regular expressions searches for any URL&#8217;s in the text and replaces them with HTML <code>&lt;a&gt;</code> links. The second expressions searchs for the Twitter @ references and again turns them into actual links. The final filter uses the regular expression that we set up earlier that removes the username from the beginning of the tweet.</p>
<pre class="brush: jscript;">
 var tweetDate = relative_time(tweet.find('pubDate').text());
     $('.loading').fadeOut(750, function() {
         $('#latest_tweet').append($('&lt;p&gt;&amp;ldquo;'+status+'&amp;rdquo; &lt;small&gt;- &lt;span&gt;'+tweetDate+'&lt;/span&gt;&lt;/small&gt;&lt;/p&gt;').hide().fadeIn(750));
     });
</pre>
<p>This final chuck extracts date and time of the tweet and passes it through the <code>relative_time</code> to turn it into a nice readable format. The last bit inserts the tweet into your website in exactly the same way as the original script.</p>
<h4>Conclusion</h4>
<div id="tutoriallinks"><a class="download" title="Download Source" href="http://www.carronmedia.com/publicfiles/twitter2.zip">Download Source</a></div>
<p>The code in the original article has proved quite successful and I think many of you have found it useful. Hopefully the new version will continue to be helpful in your projects. Please let us know if you have used this script, we would love to hear if you have found this useful in any way.</p>
<p>Thanks!</p>
<h4>Resources</h4>
<ul>
<li><a href="http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/">The original article</a></li>
<li><a href="http://apiwiki.twitter.com">Twitter API Wiki</a></li>
<li><a href="http://apiwiki.twitter.com/Twitter-REST-API-Method%3A-statuses-user_timeline">Twitter API &#8211; statuses user_timeline</a></li>
<li><a href="http://paulofierro.com/archives/459/">PHP proxy script</a></li>
<li><a href="http://www.php.net/manual/en/intro.curl.php">PHP cURL Extension</a></li>
</ul>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/0dPQ4hbcC88" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery-part-2/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>You Write The Play site launched</title>
		<link>http://www.carronmedia.com/you-write-the-play-site-launched/</link>
		<comments>http://www.carronmedia.com/you-write-the-play-site-launched/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 22:17:40 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Site launch]]></category>
		<category><![CDATA[Viral]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=394</guid>
		<description><![CDATA[This morning we launched a new viral microsite for the Daring Parings 3 writing festival at the Hampstead Theatre in London. The site, <a href="http://www.youwritetheplay.com" title="You Write The Play">www.youwritetheplay.com</a>, is an attempt to break the world record for the total number of authors for a single play.]]></description>
			<content:encoded><![CDATA[<p>This morning we launched a new viral microsite for the Daring Pairings 3 writing festival at the <a href="http://www.hampsteadtheatre.com" title="Hampstead Theatre">Hampstead Theatre</a> in London. The site, <a title="You Write The Play" href="http://www.youwritetheplay.com">www.youwritetheplay.com</a>, is an attempt to break the world record for the highest number of authors for a single play.</p>
<p>The people at the Hampstead Theatre came up with the idea to create a play using content completely written by visitor submissions and then to perform it at the theatre during their writing festival. Every visitor to the site can see the last five submitted lines and then add their own line to the play.</p>
<p>Please visit the <a title="You Write The Play" href="http://www.youwritetheplay.com">You Write The Play</a> site and submit your line. There have been some hilarious lines submitted already and the final play is set to be fantastic, if not a little bizarre.</p>
<p>Thanks!</p>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/b9e6EPBx4Ro" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/you-write-the-play-site-launched/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Why IE6 will probably out live IE7</title>
		<link>http://www.carronmedia.com/why-ie6-will-probably-out-live-ie7/</link>
		<comments>http://www.carronmedia.com/why-ie6-will-probably-out-live-ie7/#comments</comments>
		<pubDate>Mon, 28 Sep 2009 22:38:41 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[Comment]]></category>
		<category><![CDATA[Internet Explorer]]></category>
		<category><![CDATA[Microsoft]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=324</guid>
		<description><![CDATA[Microsoft&#8217;s outdated and non-standard web browser, Internet Explorer 6, has no doubt had you ripping out large clumps of hair in frustration. I know it has brought me to the point of despair on several occasions. Whether you are a web developer or not, I&#8217;m pretty sure you are aware of the array of quirks [...]]]></description>
			<content:encoded><![CDATA[<p>Microsoft&#8217;s outdated and non-standard web browser, Internet Explorer 6, has no doubt had you ripping out large clumps of hair in frustration. I know it has brought me to the point of despair on several occasions. Whether you are a web developer or not, I&#8217;m pretty sure you are aware of the array of quirks that IE6 brings to the table when trying to render the most basic of CSS rules correctly.</p>
<p>There are several well supported campaigns running in the web design community (and beyond) to bring the end to this life sapping browser. The most notable are the <a href="http://deathtoie6.com/" title="Death to IE6">Death to IE6</a> and the <a href="http://www.bringdownie6.com/" title="Bring down IE6">Bring Down IE6</a> campaigns, both of which receive my full support for trying to change the web for the better. Most of the big names on the Internet are getting in on the action as well with Facebook and YouTube (amongst others) displaying messages to users who visit their sites using IE6.</p>
<p><span id="more-324"></span></p>
<h4>The big reality check</h4>
<p>However, a conversation with a old friend of mine brought me crashing back down to Earth and to remind me of the true reality of the situation. There are an extraordinary amount of web users out there who still have to rely on (through no choice of their own) the services of IE6 to provide them access to the Internet.</p>
<p>Why? Because the corporate networks on which the users browse through to 8 hours a day are still running IE6. For example &#8211; my friend works in the IT department of a fairly large law firm in London. They have spent the last <strong>2 and a half years</strong> deploying Internet Explorer 7 to their users. The main reason for this massive project is the amount of bespoke web based applications that their business relies on to function. The money men of world don&#8217;t care if a users browsing experience is ruined by an out of date browser, especially when the bill to replace the old systems could run into the tens of thousands of pounds.</p>
<p>There is even more reason for large companies to stick with the old browser, Microsoft will still support Windows XP SP3 (<a href="http://support.microsoft.com/gp/lifesupsps#Internet_Explorer">of which IE6 is a supportable feature</a>) via their Extended Support program until <strong>April 2014</strong> &#8211; See Microsoft&#8217;s <a href="http://www.microsoft.com/windows/windows-xp/future.aspx" title="Windows XP: The facts about the future">Windows XP: The facts about the future</a> article and the <a href="http://news.bbc.co.uk/1/hi/technology/8196242.stm" title="Microsoft backs long life for IE6">Microsoft backs long life for IE6</a> BBC News report.</p>
<h4>Use your website statistics wisely</h4>
<p>This notion of large companies sticking with IE6 is supported when we looked at some global usage stats for the different browsers. The <a href="http://www.w3counter.com/globalstats.php" title="W3Counter Global Stats">W3Counter Global Stats</a> site claims that in August of 2009, IE6 still held a 14.04% share of the global Internet browser market, while <a href="http://marketshare.hitslink.com/browser-market-share.aspx?qprid=2" title="Hitlist market share stats">Hitlist market share stats</a> show the August figure to be 25.25%.</p>
<p><a href="http://marketshare.hitslink.com/browser-market-share.aspx?qprid=2" title="Hitlist market share stats"><img src="http://files.carronmedia.com/images/postimages/IE6_web_stats.jpg" alt="Hitlist IE6 global browser usage statistics" class="aligncenter" /></a></p>
<p>Of course, every website is different. You (or your web developer) must all check your own site statistics to see what your percentage of your visitors are using IE6. If the numbers seem too big for you to ignore, then don&#8217;t ignore them! Using my friends company as an example again, their website statistics show that <strong>over 40%</strong> of their visitors are using IE6, and that doesn&#8217;t include their own staff! I can only imagine how many companies out there are in the same situation.</p>
<h4>Conclusion</h4>
<p>The moral of the story is this &#8211; for the majority of websites, IE6 is here to stay. If yours or your clients site stats suggest that your visitors are still using IE6, then you should support it. Simple as that. It&#8217;s your responsibility to provide as many of your visitors with the best possible experience when they visit your site. If that means spending those extra hours fixing the problems created by IE6, then so be it. The web, after all, is for everybody to enjoy.</p>
<p>What are your views on this? We would love to hear them. Please comment below and let us know what you think.</p>
<p>Thanks!</p>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/GLCnbvxmY3Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/why-ie6-will-probably-out-live-ie7/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Display your latest Twitter update with jQuery</title>
		<link>http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/</link>
		<comments>http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/#comments</comments>
		<pubDate>Thu, 23 Jul 2009 20:14:56 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Twitter]]></category>
		<category><![CDATA[XHTML]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=325</guid>
		<description><![CDATA[UPDATE: May 2010 &#8211; There is now a new updated blog article that follows on from this article. Once you have finished reading this, please read part 2. 
I&#8217;m pretty sure that it has not escaped your attention that Twitter is an invaluable tool if you want to communicate with your clients and peers. As [...]]]></description>
			<content:encoded><![CDATA[<p><strong>UPDATE: May 2010 &#8211; There is now a new updated blog article that follows on from this article. Once you have finished reading this, please read <a href="http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery-part-2/">part 2</a>.</strong> </p>
<p>I&#8217;m pretty sure that it has not escaped your attention that <a title="Twitter home page" href="http://twitter.com">Twitter</a> is an invaluable tool if you want to communicate with your clients and peers. As you are spending all this time tweeting, it makes sense to display this information on you own website so you can draw in more followers on Twitter and get your voice heard.</p>
<p>There are quite a few tutorials available on this subject and several jQuery plugins that will display your tweets for you, all of which are very good in their individual way. However, this tutorial will show you just how easy it is to use the Twitter API tools with a tiny bit of jQuery to display your latest tweets in a fully customisable, simple and functional way.</p>
<p>First we will create a very basic HTML document to display our latest tweet. Then I will show you how to get the Twitter JavaScript code which will translate the returned data for us. We will be using our Twitter account, @<a title="Carron Media on Twitter" href="http://twitter.com/carronmedia">carronmedia</a> in the examples, please feel free to follow us.</p>
<p><a class="demo" title="View Demo" href="http://www.carronmedia.com/publicfiles/jquery-twitter-updates/">View Demo</a></p>
<p><span id="more-325"></span></p>
<h4>The Twitter API</h4>
<p>The nice people over at Twitter have provided us with a selection of tools, know as API&#8217;s, that allow us to easily use and update information on their servers. For this tutorial, we are going to concentrate on the most basic of these functions which is to simply retrieve the latest tweet for a selected Twitter account. There is an API for pretty much any programming language and plenty of documentation to back it up. Head over to the <a title="Twitter API Wiki" href="http://apiwiki.twitter.com/">Twitter API Wiki</a> where you will find all the information you need.</p>
<h5>Why bother using jQuery?</h5>
<p>Although Twitter is a wonderful service, it can suffer time to time from a bit of overcrowding and as a result, their servers can be a bit slow in returning data to your website. This can cause undesirable problems with your site and prevent the other data on the page from downloading.</p>
<p>We can reduce these problems by using the jQuery <code>$(document).ready()</code> method to load the our modified JavaScript file after the DOM has loaded and also allows to to give the end user some feedback (in the form of an loading .gif image) to let them know that some data is on its way.</p>
<h4>The basic HTML</h4>
<p>Create a new file in your project and call it <strong>index.html</strong>. Open it up and enter the following:</p>
<pre class="brush: xml;">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Strict//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
&lt;head&gt;
&lt;title&gt;My latest Tweet&lt;/title&gt;
&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=utf-8&quot; /&gt;

&lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;twitter.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;

&lt;/head&gt;
</pre>
<p>This is standard XHTML document so we have specified a DOCTYPE and a page title. The first thing we need to do is load the jQuery library. This is best achieved by loading the core file from a content delivery network such as Google&#8217;s. I have gone into more detail about this in a previous post, <a title="Extend Google Analytics with jQuery" href="http://www.carronmedia.com/extend-google-analytics-with-jquery/">Extend Google Analytics with jQuery</a>, so I won&#8217;t go into it again here.</p>
<p>We have also referenced a bespoke JavaScript file called <strong>twitter.js</strong> which we will create shortly. Make sure you get your folder path correct. For example, if you create your <strong>twitter.js</strong> is a sub-folder called &#8216;js&#8217;, the src attribute will become <code>src="js/twitter.js"</code>.</p>
<h5>Create a loading image</h5>
<p>Before we continue, head over to <a title="ajaxload.info" href="http://www.ajaxload.info/">ajaxload.info</a> which, if you have never seen this before, is a great site where you can easily create a nice loading animated .gif file. Choose your design, or <a title="Download Source" href="http://www.carronmedia.com/publicfiles/jquery-twitter-updates/twitter.zip">download the project source code</a> and use the one I generated.</p>
<p>Now lets create the body of the html file. Here we will create a <code>&lt;div&gt;</code> element that will  insert our tweet into. Also, there is a nested div within it that will hold our nice animated gif that lets the end user know that something will be loaded into this area.</p>
<p>Enter the following at the end of the file:</p>
<pre class="brush: xml;">&lt;body&gt;

&lt;div id=&quot;latest_tweet&quot;&gt;
    &lt;h3&gt;Twitter&lt;/h3&gt;
    &lt;div class=&quot;loading&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;a href=&quot;index.html&quot;&gt;Reload&lt;/a&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>There isn&#8217;t too much explanation need for this markup. The <code>&lt;div&gt;</code> with a class of &#8216;loading&#8217; will have our loading .gif as a background image and will be faded out once our tweet has been successfully loaded.</p>
<h5>Style the tweet</h5>
<p>Finally we need to style this markup, add the following in the <code>&lt;head&gt;</code> section beneath the last <code>&lt;script&gt;</code> tag (in a real live project, you should create these styles in a separate .css file):</p>
<pre class="brush: xml;">&lt;style type=&quot;text/css&quot;&gt;
body {
    font: 12px/16px normal Arial, Helvetica, sans-serif;
    color: #666;
}
#latest_tweet {
    border: 1px solid #dfdfdf;
    width: 250px;
    padding: 20px;
}
#latest_tweet small, #latest_tweet a {
    color: #7aa6cb;
}
.loading {
    background: url('ajax-loader.gif') center no-repeat;
    height: 60px;
}
&lt;/style&gt;
</pre>
<p>Again, if you put your .gif file in a different folder, make sure you change the path to it in the styles.</p>
<h4>Creating our Twitter JavaScript file</h4>
<p>First of all, we need to create a local copy of the Twitter code that will translate and format the JSON data. Go to your Internet browser of choice and enter <a href="http://twitter.com/javascripts/blogger.js">http://twitter.com/javascripts/blogger.js</a>. Depending on your browser, you will be shown the file in plain text or prompted to download it. Either way, save a copy of it into your project folder and call it <strong>twitter.js</strong>.</p>
<p>Open up your <strong>twitter.js</strong> file and you should see two functions, <code>twitterCallback2</code> and <code>relative_time</code>. The <code>twitterCallback2</code> function will translate the JSON data that we will request with jQuery and output it HTML and the <code>relative_time</code> function will format the time.</p>
<p>Lets start to modify the original code. Look for the follow line in the <code>twitterCallback2</code> function:</p>
<pre class="brush: jscript;"> statusHTML.push('&lt;li&gt;&lt;span&gt;'+status+'&lt;/span&gt; &lt;a style=&quot;font-size:85%&quot; href=&quot;http://twitter.com/'+username+'/statuses/'+twitters[i].id+'&quot;&gt;'+relative_time(twitters[i].created_at)+'&lt;/a&gt;&lt;/li&gt;');
</pre>
<p>and replace it with this line:</p>
<pre class="brush: jscript;"> statusHTML.push('&lt;p&gt;“'+status+'” – &lt;small&gt;'+relative_time(twitters[i].created_at)+'&lt;/small&gt;&lt;/p&gt;');
</pre>
<p>The original code will output a list item tag (<code>&lt;li&gt;</code>), which seems a little pointless as we are only going to display one tweet. So we have replaced it with <code>&lt;p&gt;</code> tags and reformatted the HTML a little bit.</p>
<p>Next, delete the following line at the end of the <code>twitterCallback2</code> function:</p>
<pre class="brush: jscript;">document.getElementById('latest_tweet').innerHTML = statusHTML.join('');
</pre>
<p>and in its place type:</p>
<pre class="brush: jscript;">$('.loading').fadeOut(750, function() {
    $('#latest_tweet').append($(statusHTML.join('')).hide().fadeIn(750));
});
</pre>
<p>This jQuery code will fade out the placeholder <code>&lt;div&gt;</code> which contains the loading image and then fade in our latest tweet in it&#8217;s place.</p>
<p>Finally, at the very end of the <strong>twitter.js</strong> file, type the following (make sure you change the <code>username</code> variable to the Twitter account who&#8217;s latest tweet you are going to display):</p>
<pre class="brush: jscript;">$(document).ready(function() {
    var username = 'carronmedia';
    $.getScript('http://twitter.com/statuses/user_timeline/' + username + '.json?callback=twitterCallback2&amp;count=1');
});
</pre>
<p>This uses the jQuery <code>getScript</code> method to load the Twitter API script that will return our tweet. To break this down a little bit, the twitter API will accept a few different arguments to be appended to the end of the file which we are loading. The first argument we require is called <code>callback</code>. This refers to the name of the function that we want to load the returned JSON data into. In our case, the <code>callback</code> argument is equal to the name of the first function in our <strong>twitter.js</strong> file. The second argument, <code>count</code>, simply tells the Twitter API how many tweets to return. In our case, this is set to 1.</p>
<h4>Conclusion</h4>
<p><strong>UPDATE: May 2010 &#8211; There is now a new updated blog article that follows on from this article. Once you have finished reading this, please read <a href="http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery-part-2/">part 2</a>.</strong> </p>
<div id="tutoriallinks"><a class="demo" title="View Demo" href="http://www.carronmedia.com/publicfiles/jquery-twitter-updates/">View Demo</a><a class="download" title="Download Source" href="http://www.carronmedia.com/publicfiles/jquery-twitter-updates/twitter.zip">Download Source</a></div>
<p>Twitter is a fabulous marketing tool and can really help you communicate with your end users on your site. Having the ability to automatically display your latest tweet really helps visitors relate to you as a person. It is also a handy little way of showing that your site is active and there is a real human being behind it.</p>
<p>Have you extended this code further? Do you think that there are other uses for this technique? Perhaps you have written your own jQuery plugin with it. Please comment below and let us know, we would love to hear if you have found this useful in any way.</p>
<p>Thanks!</p>
<h4>Resources</h4>
<ul>
<li><a title="Twitter home page" href="http://twitter.com">Twitter</a></li>
<li><a title="Twitter API Wiki" href="http://apiwiki.twitter.com/">Twitter API Wiki</a></li>
<li><a title="ajaxload.info" href="http://www.ajaxload.info/">ajaxload.info</a></li>
</ul>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/ZOty0tZ7Vbo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/feed/</wfw:commentRss>
		<slash:comments>26</slash:comments>
		</item>
		<item>
		<title>Carron Media website updates</title>
		<link>http://www.carronmedia.com/carron-media-website-updates/</link>
		<comments>http://www.carronmedia.com/carron-media-website-updates/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 20:06:02 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[News]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=321</guid>
		<description><![CDATA[First of all, many apologies for the lack of blog posts/tutorials recently. We&#8217;ve been rather busy in the last couple of months (which is by no means a bad thing!) on various client projects and we simply haven&#8217;t had the time to keep it up to date. We have some great articles planned for the [...]]]></description>
			<content:encoded><![CDATA[<p>First of all, many apologies for the lack of blog posts/tutorials recently. We&#8217;ve been rather busy in the last couple of months (which is by no means a bad thing!) on various client projects and we simply haven&#8217;t had the time to keep it up to date. We have some great articles planned for the near future so please keep checking back. If you have any suggestions or requests for an article, please <a href="/contact/" title="Get in touch">get in touch</a> and we will be more than happy to help out.</p>
<p>Ever since we launched Carron Media in March, there have been a few little bits of our site which we a) were not happy with or b) didn&#8217;t get around too in the first place. The main part of the site that required updating was the contact form. Although the Wordpress plugin we used has been around for ages and is used by millions of bloggers, it didn&#8217;t give us the flexibility we were looking for. So now we have hand coded our own forms and along with a new standard contact form, we have launched a new online <a href="/get-a-quote/" title="Get a quote">get a quote</a> form. </p>
<p>The second element that was in need of an update was the footer of each page. We believe the new style footer not only looks better, but is easier to use and provides a lot more information and it gives us somewhere to include our latest updates on Twitter.</p>
<p>We would love to here any feedback you may have about any aspect of the new features or of Carron Media as a whole, so please comment below. Also, you can <a href="http://twitter.com/carronmedia" title="Follow Carron Media on Twitter">follow us on Twitter</a>.</p>
<p>Thanks!</p>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/UHearyx6MNM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/carron-media-website-updates/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Extend Google Analytics with jQuery</title>
		<link>http://www.carronmedia.com/extend-google-analytics-with-jquery/</link>
		<comments>http://www.carronmedia.com/extend-google-analytics-with-jquery/#comments</comments>
		<pubDate>Sat, 16 May 2009 12:57:25 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[Google Analytics]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=257</guid>
		<description><![CDATA[For quite some time now Google Analytics has been leading the way when it comes to gathering free statistics about the web traffic of your website. I'm sure that you many of you have installed the Google code on your sites and are already using the great reporting tools it provides. However, there are a few limitations to the standard service which you may or may not have come across yet. Using the standard code, we can only track views of pages where the tracking code is installed. It becomes a little bit more difficult if we want to track file downloads and external links, where we cannot add the Google JavaScript.

The aim of this tutorial is to show you how you can modify the standard Google tracking code using the power of <a href="http://jquery.com/" title="jQuery Home Page">jQuery</a> to get extra information from your Google Analytics reports. With jQuery, we can get Google Analytics track your file downloads and clicks to external sites without having to trawl through your code and write any extra markup.]]></description>
			<content:encoded><![CDATA[<p>For quite some time now Google Analytics has been leading the way when it comes to gathering free statistics about the web traffic of your website. I&#8217;m sure that you many of you have installed the Google code on your sites and are already using the great reporting tools it provides. However, there are a few limitations to the standard service which you may or may not have come across yet. Using the standard code, we can only track views of pages where the tracking code is installed. It becomes a little bit more difficult if we want to track file downloads and external links, where we cannot add the Google JavaScript.</p>
<p>The aim of this tutorial is to show you how you can modify the standard Google tracking code using the power of <a href="http://jquery.com/" title="jQuery Home Page">jQuery</a> to get extra information from your Google Analytics reports. With jQuery, we can get Google Analytics track your file downloads and clicks to external sites without having to trawl through your code and write any extra mark up.</p>
<p>We are also going to use a new feature of Google Analytics which are known as &lsquo;Events&rsquo;. This should give you a good base for you to build your own code and extend the power of Google Analytics even more.</p>
<p><span id="more-257"></span></p>
<h4>Getting started</h4>
<p>If you haven&#8217;t already, head over to the <a href="http://www.google.com/analytics/" title="Google Analytics">Google Analytics</a> site and sign up for a free account. You will need to setup a Website Profile, which should be pretty self explanatory.</p>
<p>When you have your unique tracking code, either from your new Google account or from your current websites tracking code, take a note of the UA number, for example: UA-1234567-1. This is your unique identifier which tells Google what website to track and we will need it later on. If you already have the tracking code installed on your website, remove it now. Otherwise you could end up duplicating your stats!</p>
<h4>Google Analytics Events</h4>
<p>Before Google released the new <code>pageTracker._trackEvent()</code> function, we would use the normal <code>pageTracker._trackPageview()</code> function. To make your external links and file downloads stand out from your normal page visits, you can pass this function a modified url. For example, say we wanted to track the download of a PDF called myfile.pdf. We would add a pretend folder in front of the file name. This folder may not exist on your site, it&#8217;s there so you can easily spot downloads in your Google Analytics reports.</p>
<p>We could call this function like so:</p>
<pre class="brush: jscript;">pageTracker._trackPageview('/downloads/myfile.pdf')
</pre>
<p>You may wish to use this method instead of the newer functions, it&#8217;s up to you. However, I would recommend that you take a look into the new functions as it allows you to track much more.</p>
<p>For more information about tracking events read, the <a href="http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html" title="Google Analytics Event Tracker Guide">Google Analytics Event Tracker Guide</a>. You will see how flexible the new method is and you can expand on this tutorial to track other events on your website.</p>
<h5>Viewing you new events in Google Analytics</h5>
<p>At present, the new event tracking function is still in beta on the Google Analytics site and not all accounts have access to view them by default. However, this is not a problem as you can add it in manually. When you are logged into your Analytics, type the following url into your browser: https://www.google.com/analytics/reporting/events. This will take you to events page. Once there, click on the &#8220;Add to Dashboard&#8221; button above the report and this will add the Events Tracking Overview section to your dashboard.</p>
<h4>Integrating jQuery</h4>
<p>There are a couple options available to you when you load the jQuery code; you can download a copy from the <a href="http://jquery.com/" title="jQuery Home Page">jQuery</a> site and call it locally, or as we will do, call it directly from the Google code library. For more information why this is the better way to load jQuery, read <a href="http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/" title="3 reasons why you should let Google host jQuery for you">3 reasons why you should let Google host jQuery for you</a>.</p>
<p>In the <code>&lt;head&gt;&lt;/head&gt;</code> section of your HTML, copy and paste the following code.</p>
<pre class="brush: jscript;">&lt;script src=&quot;http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
</pre>
<p>This load the minimised version of jQuery 1.3.2, which is the current verison at the time of writing, you may wish to check to see if there is a newer version available. For more information about jQuery, take a look at the <a href="http://docs.jquery.com/Main_Page" title="jQuery Documentation">jQuery Documentation</a>.</p>
<h4>Writing the custom tracking code</h4>
<p>Still in the <code>&lt;head&gt;&lt;/head&gt;</code>, directly beneath the code we have just inserted, enter the following:</p>
<pre class="brush: jscript;">&lt;script type=&quot;text/javascript&quot;&gt;
$(document).ready(function(){

    var gaJsHost = ((&quot;https:&quot; == document.location.protocol) ? &quot;https://ssl.&quot; : &quot;http://www.&quot;);
    $.getScript(gaJsHost + &quot;google-analytics.com/ga.js&quot;, function(){

        try {
            var pageTracker = _gat._getTracker(&quot;UA-xxxxxxx-x&quot;);
            pageTracker._trackPageview();
        } catch(err) {}

        var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
</pre>
<p>Instead of loading the Google Javascript directly in the mark up, we are using the jQuery <code>$(document).ready</code> function to load the code as soon as the DOM is ready, which means that our code is ready before any of the page content gets loaded. Therefore we can target elements, such as links, when they are loaded by the browser.</p>
<p>Next, we include the standard Google tracking code to register that the current page has been visited. The difference here is that we are using another jQuery function, <code>$.getScript</code>, to load the Google JavaScript file and then create a function to run once the file is loaded. Make sure you replace the UA-xxxxxxx-x with your own unique UA number. We then set a variable called <code>filetypes</code> which holds a regular expression to find any links with popular file extensions, you can add or remove any file extensions you wish.</p>
<h5>Outbound links</h5>
<p>Now we get to the part where we add the code which will actually start tracking the additional links. We will start with all of the external links on the page.</p>
<p>Add the following code to your script:</p>
<pre class="brush: jscript;">        $('a').each(function(){
            var href = $(this).attr('href');

            if ((href.match(/^https?\:/i)) &amp;&amp; (!href.match(document.domain))){
                $(this).click(function() {
                    var extLink = href.replace(/^https?\:\/\//i, '');
                    pageTracker._trackEvent('External', 'Click', extLink);
                });
            }
</pre>
<p>The <code>$('a').each</code> function will target each <code>&lt;a&gt;</code> tag in turn and execute the code within the function itself against that tag. The first part of this function is to set a variable, <code>href</code>, which will hold the value of the <code>href</code> attribute of each <code>&lt;a&gt;</code> tag.</p>
<p>Our first <code>if</code> statement performs two checks. It is making use of the <code>.match</code> function to check to see if the value of our <code>href</code> variable either starts with <code>http:</code> or <code>https:</code> (using a simple regular expression) and that it does not contain the current domain of the website (i.e. it is external).</p>
<p>If this <code>if</code> statement is returned true, we then add a click event to the current <code>&lt;a&gt;</code> tag the our script is currently looking at. When this click event is triggered, we use another regular expression to strip the <code>http://</code> or <code>https://</code> from the link path. Finally, we use Google&#8217;s <code>pageTracker._trackEvent</code> function to send the event details to our Google Analytics account. The first option for the function it to set the link category, I have used &#8216;External&#8217;. The next option is the to set the action, this has been set to &#8216;Click&#8217;. The last option is to sent the link label. This is set to the url of the external link.</p>
<h5>Mailto: links</h5>
<p>The next type of link we are going to target are any email address links that may be on the current page. As you know, the email address is preceeded with <code>mailto:</code>, so we can easily pick them out with jQuery.</p>
<p>Directly after the last <code>if</code> statement, add the following code to your script:</p>
<pre class="brush: jscript;">            else if (href.match(/^mailto\:/i)){
                $(this).click(function() {
                    var mailLink = href.replace(/^mailto\:/i, '');
                    pageTracker._trackEvent('Email', 'Click', mailLink);
                });
            }
</pre>
<p>This works in exactly the same way as the external link <code>if</code> statement. We use a regular expression to find any email links, clean the link up by removing the preceeding <code>mailto:</code> and then fire off the Google tracking event.</p>
<h5>File downloads</h5>
<p>The last type of links we are going to track are file downloads. Again, using a regular expression, we will check each link and match ita againsts the <code>filetypes</code> variable we created earlier.</p>
<p>Add the following code to your script under the last statement:</p>
<pre class="brush: jscript;">            else if (href.match(filetypes)){
                $(this).click(function() {
                    var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                    var filePath = href.replace(/^https?\:\/\/(www.)mydomain\.com\//i, '');
                    pageTracker._trackEvent('Download', 'Click - ' + extension, filePath);
                });
            }
        });
    });
});
&lt;/script&gt;
</pre>
<p>Again, the process is the same, but this time we are going to extract the file extension into a variable called <code>extension</code> using yet another regular expression. If the link is an absolute link (i.e. it has the full http://www.mydomain.com/ in the file path), we removed the protocol and domain name as we don&#8217;t really need this in our Google Analytics reports as we already know that the link is local to our site. Make sure you replace <code>mydomain.com</code> with your own domain name. </p>
<p>Here is the code in full (with the gaps removed so it fits on the page better):</p>
<pre class="brush: jscript;">&lt;script type=&quot;text/javascript&quot;&gt;
$(document).ready(function(){

    var gaJsHost = ((&quot;https:&quot; == document.location.protocol) ? &quot;https://ssl.&quot; : &quot;http://www.&quot;);
    $.getScript(gaJsHost + &quot;google-analytics.com/ga.js&quot;, function(){

        try {
            var pageTracker = _gat._getTracker(&quot;UA-xxxxxxx-x&quot;);
            pageTracker._trackPageview();
        } catch(err) {}

        var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;

        $('a').each(function(){
            var href = $(this).attr('href');

            if ((href.match(/^https?\:/i)) &amp;&amp; (!href.match(document.domain))){
                $(this).click(function() {
                    var extLink = href.replace(/^https?\:\/\//i, '');
                    pageTracker._trackEvent('External', 'Click', extLink);
                });
            }
            else if (href.match(/^mailto\:/i)){
                $(this).click(function() {
                    var mailLink = href.replace(/^mailto\:/i, '');
                    pageTracker._trackEvent('Email', 'Click', mailLink);
                });
            }
            else if (href.match(filetypes)){
                $(this).click(function() {
                    var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                    var filePath = href.replace(/^https?\:\/\/(www.)mydomain\.com\//i, '');
                    pageTracker._trackEvent('Download', 'Click - ' + extension, filePath);
                });
            }
        });
    });
});
&lt;/script&gt;
</pre>
<h4>Conclusion</h4>
<p>With the power of jQuery and the new Google &lsquo;Events&rsquo;, it is clear that you can take your website statistics further and produce more meaningful reports. This will help you gain a better understanding of how your website is being used and what your users and looking for, which can only be better for all concerned. </p>
<p>You can download the full code below, make sure you add in your own UA number and domain name.</p>
<div class="downloadlink">
<p><a href="http://www.carronmedia.com/publicfiles/extendga.js" title="extendga.js Download">extendga.js</a> <small>1.62kb</small></p>
</div>
<p>Have you extended this code further? Have you found any other uses for the new Google &lsquo;Events&rsquo;? Perhaps you have written your own jQuery plugin with it. Please comment below and let us know, we would love to hear if you have found this useful in any way.</p>
<p>Thanks!</p>
<h4>Resources</h4>
<ul>
<li><a href="http://jquery.com/" title="jQuery Home Page">jQuery</a></li>
<li><a href="http://docs.jquery.com/Main_Page" title="jQuery Documentation">jQuery Documentation</a></li>
<li><a href="http://www.google.com/analytics/" title="Google Analytics">Google Analytics</a></li>
<li><a href="http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html" title="Google Analytics Event Tracker Guide">Google Analytics Event Tracker Guide</a></li>
<li><a href="http://encosia.com/2008/12/10/3-reasons-why-you-should-let-google-host-jquery-for-you/" title="3 reasons why you should let Google host jQuery for you">3 reasons why you should let Google host jQuery for you</a></li>
</ul>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/-kTVMXyZbl0" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/extend-google-analytics-with-jquery/feed/</wfw:commentRss>
		<slash:comments>27</slash:comments>
		</item>
		<item>
		<title>Under used HTML tags</title>
		<link>http://www.carronmedia.com/under-used-html-tags/</link>
		<comments>http://www.carronmedia.com/under-used-html-tags/#comments</comments>
		<pubDate>Sun, 12 Apr 2009 11:31:20 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Tags]]></category>
		<category><![CDATA[XHTML]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=100</guid>
		<description><![CDATA[The current specification of HTML has been around for nearly 10 years now and us web developers all use this fundamental language on a daily basis. However, due to our busy schedules, there are a few HTML tags that tend to get either neglected or used in the wrong way.

I'm going to list a few of the more important tags here with some examples of their use. Hopefully this article will provide you with some guidance to why we should use them.]]></description>
			<content:encoded><![CDATA[<p>The current specification of HTML has been around for nearly 10 years now and us web developers all use this fundamental language on a daily basis. However, due to our busy schedules, there are a few HTML tags that tend to get either neglected or used in the wrong way.</p>
<p>I&#8217;m going to list a few of the more important tags here with some examples of their use. Hopefully this article will provide you with some guidance to why we should use them.</p>
<h4>1. &lt;address&gt;</h4>
<p>As the name suggests, the <code>&lt;address&gt;</code> tag is used to display contact details of the author of a web page. This means that you can standardised the format of either yours or your users contact details to make them easily identifiable.</p>
<p>The important thing to note is that the <code>&lt;address&gt;</code> tag is not limited to just a postal address, but you can include any contact details, such as a name, email, phone number, URL, etc.</p>
<p>For example:</p>
<pre class="brush: xml;">&lt;address&gt;
    Written by: Ian Harris&lt;br /&gt;
    Email: &lt;a href=&quot;mailto:info@example.com&quot;&gt;info@example.com&lt;/a&gt;&lt;br /&gt;
    Phone: 01234 567 890
&lt;/address&gt;
</pre>
<p>Although the <code>&lt;address&gt;</code>tag should be used where possible, that is a better alternative in the form of microformats. Take a look at the <a title="Microformats" href="http://microformats.org/wiki/hcard">hCard Microformats wiki page</a> for more information.</p>
<p><span id="more-100"></span></p>
<h4>2. &lt;abbr&gt; &amp; &lt;acronym&gt;</h4>
<p>The <code>&lt;abbr&gt;</code> and <code>&lt;acronym&gt;</code> are two very similar tags that are used to provide the user with additional information about an abbreviated phrase. The <code>&lt;abbr&gt;</code> tag is used to define terms such as CMS (Content Management System). The <code>&lt;acronym&gt;</code> tag defines an abbreviated term as if it can be spoken as a word, for example Radar (Radio Detection and Ranging). These tags are incredibly useful because when the user hovers their mouse over the abbreviated phrase, the full defined description is displayed as a tool tip.</p>
<p>Here is the code for these two examples:</p>
<pre class="brush: xml;">&lt;abbr title=&quot;Content Management System&quot;&gt;CMS&lt;/abbr&gt;</pre>
<pre class="brush: xml;">&lt;acronym title=&quot;Radio Detection and Ranging&quot;&gt;Radar&lt;/acronym&gt;</pre>
<p>Hover over the following to see them in action: <abbr title="Content Management System">CMS</abbr> and <acronym title="Radio Detection and Ranging">Radar</acronym></p>
<p>It is common practice to style these tags with a dotted bottom border so that users can identify that these tags have additional information attached to them:</p>
<pre class="brush: css;">abbr, acronym {
    cursor: help;
    border-bottom: 1px dotted #000;
}
</pre>
<p>Another good reason for using these tags is that they are used by screen readers and search engines to draw extra information from your content. This helps you to create accessible and search engine friendly content, which of course is what most of us are trying to achieve.</p>
<h4>3. &lt;cite&gt;</h4>
<p>The <code>&lt;cite&gt;</code> tag is used to indicate a citation and allows you to reference the source of information. This tag is probably most commonly used in conjunction with the <code>&lt;q&gt;</code> and <code>&lt;blockquote&gt;</code> tags as it allows you to specify the source of the quote.</p>
<p>As with the <code>&lt;abbr&gt;</code> and <code>&lt;acronym&gt;</code> tags, you can add the <code>title</code>attribute to display some extra information when the user hovers their mouse of it.</p>
<p>For example:</p>
<pre class="brush: xml;">&lt;p&gt;&lt;q&gt;O Romeo, Romeo, wherefore art thou Romeo?&lt;q&gt; - &lt;cite title=&quot;Romeo And Juliet Act 2, scene 2, 33–49&quot;&gt;William Shakespeare&lt;/cite&gt;&lt;/p&gt;
</pre>
<p><q>O Romeo, Romeo, wherefore art thou Romeo?</q> – <cite title="Romeo And Juliet Act 2, scene 2, 33–49">William Shakespeare</cite></p>
<p>It&#8217;s worth pointing out that the <code>&lt;q&gt;</code> tag has only just been supported by Internet Explorer in version 8.</p>
<h4>4. &lt;del&gt; &amp; &lt;ins&gt;</h4>
<p>The <code>&lt;del&gt;</code> and <code>&lt;ins&gt;</code> stand for deletion and insertion respectively. It&#8217;s quite common these days for an author to show the end user where content has been edited after it&#8217;s initial publication, especially when the content can be updated by more that one person. The <code>&lt;del&gt;</code>tag will add a strike-through to it&#8217;s contents, where as the <code>&lt;ins&gt;</code> will add an underline.</p>
<pre class="brush: xml;">&lt;p&gt;My favourite type of music is &lt;del&gt;rock&lt;/del&gt; &lt;ins&gt;reggae&lt;/ins&gt;.&lt;/p&gt;
</pre>
<p>This is displayed as: My favourite type of music is <del>rock</del> <ins>reggae</ins>.</p>
<h4>5. &lt;dl&gt;, &lt;dt&gt; &amp; &lt;dd&gt;</h4>
<p>You are no doubt aware of the <code>&lt;ul&gt;</code> and <code>&lt;ol&gt;</code> tags and their uses, but there is another list called a <em>definition list</em> which looks like <code>&lt;dl&gt;</code>. In the traditional sense, this type of list should be used if you create a list of definition terms with associated descriptions. However, <a title="W3C list specification" href="http://www.w3.org/TR/REC-html40/struct/lists.html">W3C list specification</a> seems to indicate that you can use the <code>&lt;dl&gt;</code> tag to list any terms where there is a direct relationship between them.</p>
<p>The <code>&lt;dl&gt;</code> tag has two child elements which are <code>&lt;dt&gt;</code> and <code>&lt;dd&gt;</code> which stand for <em>definition term</em> and <em>definition definition</em>. There can be multiple <code>&lt;dd&gt;</code> tags associated with each <code>&lt;dt&gt;</code>.</p>
<p>For example:</p>
<pre class="brush: xml;">&lt;dl&gt;
    &lt;dt&gt;HTML&lt;/dt&gt;
        &lt;dd&gt;Hypertext Markup Language&lt;/dd&gt;
&lt;/dl&gt;
&lt;dl&gt;
    &lt;dt&gt;The FA Cup Final&lt;/dt&gt;
        &lt;dd&gt;When: 30th May, 2009 3pm&lt;/dd&gt;
        &lt;dd&gt;Where: Wembley Stadium&lt;/dd&gt;
&lt;/dl&gt;
</pre>
<p>This is displayed as:</p>
<dl>
<dt>HTML</dt>
<dd>Hypertext Markup Language</dd>
</dl>
<dl>
<dt>The FA Cup Final</dt>
<dd>When: 30th May, 2009 3pm</dd>
<dd>Where: Wembley Stadium</dd>
</dl>
<h4>6. &lt;sub&gt; &amp; &lt;sup&gt;</h4>
<p>The final two tags in this list are <em>subscript</em>, <code>&lt;sub&gt;</code> and <em>superscript</em>, <code>&lt;sup&gt;</code>. The same results can be achieve using CSS, but whats the point when you can use these two built in HTML tags.</p>
<p>There usage can be seen in the following examples:</p>
<pre class="brush: xml;">&lt;p&gt;The chemical formula for water is H&lt;sub&gt;2&lt;/sub&gt;O.&lt;/p&gt;
</pre>
<p>The chemical formula for water is H<sub>2</sub>O.</p>
<pre class="brush: xml;">&lt;p&gt;Today is the 12&lt;sup&gt;th&lt;/sup&gt; April.&lt;/p&gt;
</pre>
<p>Today is the 12<sup>th</sup> April.</p>
<h4>Conclusion</h4>
<p>In reality, you may rarely use some of the tags listed above. However, you should definitely keep them in mind and make sure you use them correctly when the need arises. The key to writing semantic code is to use the correct HTML tags for the correct application.</p>
<p>Semantically written code will help you product search engine friendly and accessible content, which after all, is what we should all be doing.</p>
<h4>Resources</h4>
<ul>
<li><a title="Wikipedia article about HTML" href="http://en.wikipedia.org/wiki/HTML">Wikipedia article about HTML</a></li>
<li><a title="Microformats" href="http://microformats.org/wiki/hcard">hCard Microformats wiki</a></li>
<li><a title="W3C list specification" href="http://www.w3.org/TR/REC-html40/struct/lists.html">W3C list specification</a></li>
</ul>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/5lnSie1WxKU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/under-used-html-tags/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>5 Simple but useful JavaScript snippits</title>
		<link>http://www.carronmedia.com/5-simple-but-useful-javascript-snippits/</link>
		<comments>http://www.carronmedia.com/5-simple-but-useful-javascript-snippits/#comments</comments>
		<pubDate>Thu, 26 Mar 2009 23:55:56 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=82</guid>
		<description><![CDATA[JavaScript can be employed on your website to perform an whole multitude of simple, but quite effective, tasks that make your job as a web developer that little bit easier. Over time, we have compiled a library of these little JavaScript snippets and we have listed a few of our favourites here.]]></description>
			<content:encoded><![CDATA[<p>JavaScript can be employed on your website to perform an whole multitude of simple, but quite effective, tasks that make your job as a web developer that little bit easier. Over time, we have compiled a library of these little JavaScript snippets and we have listed a few of our favourites here.</p>
<h4>1. &lsquo;Previous Page&rsquo; link</h4>
<p>This snippet will take the user back to the previous page that they have viewed. Pretty much like the standard browser back button really:</p>
<pre class="brush: xml;">&lt;a href=&quot;javascript:history.back(1)&quot;&gt;Previous Page&lt;/a&gt;
</pre>
<p><span id="more-82"></span></p>
<h4>2. &lsquo;Print this page&rsquo; links</h4>
<p>I&#8217;ve read quite a few mixed opinions about adding a link that allows users to print the current page. Some developers think that their users will already know how to print the page using the browsers toolbar and don&#8217;t need us cluttering our pages with unnecessary links. Others believe that we should make it easy for the user and remind them that they can print this content if they so wish. I am with the latter, but whatever your opinion, here it how you add a print link:</p>
<pre class="brush: xml;">&lt;a href=&quot;#&quot; onclick=&quot;window.print();return false;&quot;&gt;Print&lt;/a&gt;
</pre>
<h4>3. Close the current browser window</h4>
<p>On occasions, you might need want to give the user the option to easily close the current browser window. For example, you have created a CMS that uses pop-up top display information. This snippit will close the current browser window (or tab):</p>
<pre class="brush: xml;">&lt;a href=&quot;javascript:window.close();&quot;&gt;Click to Close&lt;/a&gt;
</pre>
<h4>4. Confirm prompt</h4>
<p>If you are asking the user to perform a certain action, like deleting something, you can prompt them to confirm that they definitely want to go ahead. This snippit intercepts by prompting with a Yes/No box and a message of your choice. If the user selects Yes, it will carry on to the URL in the link. Selecting No will just cancel the action.</p>
<pre class="brush: xml;">&lt;a href=&quot;delete.php&quot; onclick=&quot;return confirm('Are you sure you want to delete this?')&quot;&gt;Delete&lt;/a&gt;
</pre>
<h4>5. Replace broken images</h4>
<p>Sometimes you may link to images that are hosted on other domains, such as photos in your Flickr account. As this is external, you cannot guarantee that this content will always be available and if the site hosting the image was to go offline, you would be left with that nasty red cross that gives the impression that you don&#8217;t look after your site. The snippet below will display a default image if the external image is unavailable (obviously, you should only link to images where you have permission to do so, nobody likes a bandwidth thief).</p>
<pre class="brush: xml;">&lt;img src=&quot;http://www.mydomain.com/image.jpg&quot;
onerror='this.src=&quot;/images/unavailable.png&quot;' /&gt;
</pre>
<p>I hope these are useful to you, they have certainly helped us. Thanks.</p>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/g2ODCGvpfNs" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/5-simple-but-useful-javascript-snippits/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>UK Postal Counties List</title>
		<link>http://www.carronmedia.com/uk-postal-counties-list/</link>
		<comments>http://www.carronmedia.com/uk-postal-counties-list/#comments</comments>
		<pubDate>Sat, 21 Mar 2009 01:01:15 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[Tips & Tricks]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[UK Counties]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=88</guid>
		<description><![CDATA[On a recent project, we were required to create a drop down list to display the UK's counties as part of a web form collecting users addresses. We assumed that this would be a pretty standard task and that there would be an abundance of pre-configured lists available on the Internet for download. After about an hour of research, it became clear that it was not going to be that simple. All of the lists we unearthed were either incomplete or out of date and it seems that we were not the first developers to run into this trouble.]]></description>
			<content:encoded><![CDATA[<p>On a recent project, we were required to create a drop down list to display the UK&#8217;s counties as part of a web form collecting users addresses. We assumed that this would be a pretty standard task and that there would be an abundance of pre-configured lists available on the Internet for download. After about an hour of research, it became clear that it was not going to be that simple. All of the lists we unearthed were either incomplete or out of date and it seems that we were not the first developers to run into this trouble.</p>
<p>You can see how it is easy to get it wrong though, take a look at the <a href="http://en.wikipedia.org/wiki/List_of_counties_of_the_United_Kingdom" title="Wikipedia list of UK counties">Wikipedia list of UK counties</a>. The list of counties has changed quite considerably over time, especially in Wales.</p>
<p><span id="more-88"></span><br />
As we were only interested in postal addresses for the web form, we decided it would be quicker and easier to compile our own list using the postal county data in this Wikipedia article. So here is a zipped file containing the HTML list as well as a XML list we created of the current UK postal counties. We hope this helps you out in some way. It may be worth just keeping these lists on file somewhere, you never know when you may need them.</p>
<div class="downloadlink">
<p><a href="http://www.carronmedia.com/publicfiles/UKCounties.zip" title="UKCounties.zip Download">UKCounties.zip</a> <small>1.55kb</small></p>
</div>
<h4>Resources</h4>
<ul>
<li><a href="http://en.wikipedia.org/wiki/List_of_counties_of_the_United_Kingdom" title="Wikipedia list of UK counties">Wikipedia list of UK counties</a></li>
</ul>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/x7Z9pcjh6nM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/uk-postal-counties-list/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Create an RSS feed with PHP</title>
		<link>http://www.carronmedia.com/create-an-rss-feed-with-php/</link>
		<comments>http://www.carronmedia.com/create-an-rss-feed-with-php/#comments</comments>
		<pubDate>Wed, 18 Mar 2009 23:54:07 +0000</pubDate>
		<dc:creator>Ian Harris</dc:creator>
				<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[RSS]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://www.carronmedia.com/?p=86</guid>
		<description><![CDATA[Having an RSS feed on your website is a great way of sharing your content with the rest of the Internet. It's not a new technology and it's probably something that you use on a daily basis. If you have a blog or use any form of CMS, that software will most likely handle the creation of your RSS feed for you.

Sometimes, however, it might be necessary for you to create a RSS feed yourself. Perhaps you have just won a new client who's current site has a old bespoke CMS which they like and want to keep, but you want to be able to publish their updated content via RSS. Hopefully this tutorial will help you to achieve this.]]></description>
			<content:encoded><![CDATA[<p>Having an RSS feed on your website is a great way of sharing your content with the rest of the Internet. It&#8217;s not a new technology and it&#8217;s probably something that you use on a daily basis. If you have a blog or use any form of CMS, that software will most likely handle the creation of your RSS feed for you.</p>
<p>Sometimes, however, it might be necessary for you to create a RSS feed yourself. Perhaps you have just won a new client who&#8217;s current site has a old bespoke CMS which they like and want to keep, but you want to be able to publish their updated content via RSS. Hopefully this tutorial will help you to achieve this.</p>
<h4>What is RSS?</h4>
<p>RSS, in its current form, stands for <strong>Really Simple Syndication</strong> and is a family of web formats to publish frequently updated content. The RSS Feed (as it is commonly known) can then be read by the users feed reading software or by another website which wishes to &#8217;syndicate&#8217; the content of that feed.</p>
<p><span id="more-86"></span><br />
The RSS format is based on XML that is built using standardised tags. Here is an example of a basic RSS document, we will be generating something similar using PHP later in this tutorial:</p>
<pre class="brush: xml;">&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;
&lt;rss version=&quot;2.0&quot;&gt;
    &lt;channel&gt;
        &lt;title&gt;My RSS feed&lt;/title&gt;
        &lt;link&gt;http://www.mywebsite.com/&lt;/link&gt;
        &lt;description&gt;This is an example RSS feed&lt;/description&gt;
        &lt;language&gt;en-us&lt;/language&gt;
        &lt;copyright&gt;Copyright (C) 2009 mywebsite.com&lt;/copyright&gt;
        &lt;item&gt;
            &lt;title&gt;My News Story 3&lt;/title&gt;
            &lt;description&gt;This is example news item&lt;/description&gt;
            &lt;link&gt;http://www.mywebsite.com/news3.html&lt;/link&gt;
            &lt;pubDate&gt;Mon, 23 Feb 2009 09:27:16 +0000&lt;/pubDate&gt;
        &lt;/item&gt;
        &lt;item&gt;
            &lt;title&gt;My News Story 2&lt;/title&gt;
            &lt;description&gt;This is example news item&lt;/description&gt;
            &lt;link&gt;http://www.mywebsite.com/news2.html&lt;/link&gt;
            &lt;pubDate&gt;Wed, 14 Jan 2009 12:00:00 +0000&lt;/pubDate&gt;
        &lt;/item&gt;
        &lt;item&gt;
            &lt;title&gt;My News Story 1&lt;/title&gt;
            &lt;description&gt;This is example news item&lt;/description&gt;
            &lt;link&gt;http://www.mywebsite.com/news1.html&lt;/link&gt;
            &lt;pubDate&gt;Wed, 05 Jan 2009 15:57:20 +0000&lt;/pubDate&gt;
        &lt;/item&gt;
    &lt;/channel&gt;
&lt;/rss&gt;
</pre>
<p>Take a look at the <a title="RSS on Wikipedia" href="http://en.wikipedia.org/wiki/RSS">RSS Wikipedia page</a> for a full history of RSS and it&#8217;s various different versions.</p>
<h4>Creating the feed</h4>
<p>As we know, RSS is made up of standardised XML tags which you would normally find in a flat XML file. What we are going to do is create this standard XML data dynamically using PHP. This means that the URL for our feed will end with the .php extension, but we will tidy this up later in the tutorial.</p>
<p>So, lets start building the PHP script. The first thing we are going to do is tell PHP what type of data we would like to output (I am going to break each section of the script down, but I will include it in full at the end):</p>
<pre class="brush: php;">&lt;?php
    header(&quot;Content-Type: application/rss+xml; charset=ISO-8859-1&quot;);
</pre>
<p>The <code>header()</code> function that we have called is telling PHP to output our data using the XML MIME type as well as to use the ISO-8859-1 character set. This makes sure that our content is delivered to the users in the correct format.</p>
<p>Now we are going to define our database connection details and create the header XML tags for our RSS feed. I&#8217;m going to statically assign the feed information tags just to keep it simple, however, you may wish to expand on this to dynamically set these. That way, you can re-use this code as a function or even go a step further and use it to build your own PHP class. The actual feed data will be kept in a variable called <code>$rssfeed</code>.</p>
<pre class="brush: php;">    DEFINE ('DB_USER', 'my_username');
    DEFINE ('DB_PASSWORD', 'my_password');
    DEFINE ('DB_HOST', 'localhost');
    DEFINE ('DB_NAME', 'my_database'); 

    $rssfeed = '&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;';
    $rssfeed .= '&lt;rss version=&quot;2.0&quot;&gt;';
    $rssfeed .= '&lt;channel&gt;';
    $rssfeed .= '&lt;title&gt;My RSS feed&lt;/title&gt;';
    $rssfeed .= '&lt;link&gt;http://www.mywebsite.com&lt;/link&gt;';
    $rssfeed .= '&lt;description&gt;This is an example RSS feed&lt;/description&gt;';
    $rssfeed .= '&lt;language&gt;en-us&lt;/language&gt;';
    $rssfeed .= '&lt;copyright&gt;Copyright (C) 2009 mywebsite.com&lt;/copyright&gt;';
</pre>
<p>Next, we need to extract our data by looping through our MySQL database to create the <code>&lt;item&gt;</code> tags. I&#8217;m not going to explain this part in too much details as it&#8217;s not point of this tutorial and you may do this differently. We are going to assume that our MySQL table (&#8220;mytable&#8221;) has columns called <em>title</em>, <em>description</em>, <em>link</em> and <em>date</em> which hold the relevant data:</p>
<pre class="brush: php;">    $connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
        or die('Could not connect to database');
    mysql_select_db(DB_NAME)
        or die ('Could not select database');

    $query = &quot;SELECT * FROM mytable ORDER BY date DESC&quot;;
    $result = mysql_query($query) or die (&quot;Could not execute query&quot;);

    while($row = mysql_fetch_array($result)) {
        extract($row);

        $rssfeed .= '&lt;item&gt;';
        $rssfeed .= '&lt;title&gt;' . $title . '&lt;/title&gt;';
        $rssfeed .= '&lt;description&gt;' . $description . '&lt;/description&gt;';
        $rssfeed .= '&lt;link&gt;' . $link . '&lt;/link&gt;';
        $rssfeed .= '&lt;pubDate&gt;' . date(&quot;D, d M Y H:i:s O&quot;, strtotime($date)) . '&lt;/pubDate&gt;';
        $rssfeed .= '&lt;/item&gt;';
    }

    $rssfeed .= '&lt;/channel&gt;';
    $rssfeed .= '&lt;/rss&gt;';

    echo $rssfeed;
?&gt;
</pre>
<p>The first part of this section connects to the MySQL database using the constants which we defined at the start of the script. Then we perform a basic SQL query to pull out all our data from the database in date order. The final part of the query, <code>DESC</code>, ensures that the newest content will appear first in the users RSS reader.</p>
<p>Next, we look at each row of data from the results of the query using a <code>while</code> loop. In each loop cycle, the first action performed is the <code>extract()</code> function to create a set of variables that take the name of the columns of the database, in my case <code>$title</code>, <code>$description</code>, <code>$link</code>, and <code>$date</code>. We then add the data contained in these variables to our main <code>$rssfeed</code> variable. When it reaches the final row of data, the <code>while</code> loop ends and we apply the closing XML tags.</p>
<p>The final step of the script is to actually output the data we have collected. This is simply done by echoing the <code>$rssfeed</code> variable. Here is the code in full:</p>
<pre class="brush: php;">&lt;?php
    header(&quot;Content-Type: application/rss+xml; charset=ISO-8859-1&quot;);

    DEFINE ('DB_USER', 'my_username');
    DEFINE ('DB_PASSWORD', 'my_password');
    DEFINE ('DB_HOST', 'localhost');
    DEFINE ('DB_NAME', 'my_database'); 

    $rssfeed = '&lt;?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?&gt;';
    $rssfeed .= '&lt;rss version=&quot;2.0&quot;&gt;';
    $rssfeed .= '&lt;channel&gt;';
    $rssfeed .= '&lt;title&gt;My RSS feed&lt;/title&gt;';
    $rssfeed .= '&lt;link&gt;http://www.mywebsite.com&lt;/link&gt;';
    $rssfeed .= '&lt;description&gt;This is an example RSS feed&lt;/description&gt;';
    $rssfeed .= '&lt;language&gt;en-us&lt;/language&gt;';
    $rssfeed .= '&lt;copyright&gt;Copyright (C) 2009 mywebsite.com&lt;/copyright&gt;';

    $connection = @mysql_connect(DB_HOST, DB_USER, DB_PASSWORD)
        or die('Could not connect to database');
    mysql_select_db(DB_NAME)
        or die ('Could not select database');

    $query = &quot;SELECT * FROM mytable ORDER BY date DESC&quot;;
    $result = mysql_query($query) or die (&quot;Could not execute query&quot;);

    while($row = mysql_fetch_array($result)) {
        extract($row);

        $rssfeed .= '&lt;item&gt;';
        $rssfeed .= '&lt;title&gt;' . $title . '&lt;/title&gt;';
        $rssfeed .= '&lt;description&gt;' . $description . '&lt;/description&gt;';
        $rssfeed .= '&lt;link&gt;' . $link . '&lt;/link&gt;';
        $rssfeed .= '&lt;pubDate&gt;' . date(&quot;D, d M Y H:i:s O&quot;, strtotime($date)) . '&lt;/pubDate&gt;';
        $rssfeed .= '&lt;/item&gt;';
    }

    $rssfeed .= '&lt;/channel&gt;';
    $rssfeed .= '&lt;/rss&gt;';

    echo $rssfeed;
?&gt;
</pre>
<p>I mentioned earlier that I would tidy up the .php extension of the feed. I don&#8217;t know about you, but I find this a little bit ugly. When you see RSS feeds that have been generated by Wordpress for example, you don&#8217;t see the actual file name, you just get the containing folder. To do this, create a folder in the root directory of the site and call it &#8216;feed&#8217;. Create a file in this new folder called &#8216;index.php&#8217; and copy the code above into it. This leaves us with a nicer looking feed URL, in the case of this example, http://www.mydomain.com/feed/.</p>
<p>It really isn&#8217;t that necessary to tidy the feed URL, but I think it just looks a little neater. </p>
<h4>Conclusion</h4>
<p>Now that you have created your feed, you can link to it from your site or publish it using a service such as <a href="http://www.feedburner.com" title="FeedBurner">FeedBurner</a>. But there is an extra step which will allow your visitor&#8217;s browsers to automatically detect the RSS feed on your site. In the <code>&lt;head&gt;</code> section of you pages, include the following tag (obviously changing the URL to your feed):</p>
<pre class="brush: xml;">&lt;link rel=&quot;alternate&quot; href=&quot;/feed/&quot; title=&quot;My RSS feed&quot; type=&quot;application/rss+xml&quot; /&gt;
</pre>
<p>Thanks for reading, it&#8217;s the first tutorial we have published and we hope it helps you out in some way. Please leave a comment below, we would love you hear what you have to say.</p>
<h4>Resources</h4>
<ul>
<li><a href="http://en.wikipedia.org/wiki/RSS" title="RSS on Wikipedia">RSS Wikipedia page</a></li>
<li><a href="http://uk.php.net/function.extract" title="The PHP extract() function">PHP.net &#8211; extract() function</a></li>
<li><a href="http://validator.w3.org/feed/" title="W3C RSS feed validation">W3C RSS feed validation</a></li>
<li><a href="http://www.feedburner.com" title="FeedBurner">FeedBurner</a></li>
</ul>
<img src="http://feeds.feedburner.com/~r/CarronMedia/~4/toe8zeatZvo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/create-an-rss-feed-with-php/feed/</wfw:commentRss>
		<slash:comments>40</slash:comments>
		</item>
	</channel>
</rss><!-- Dynamic page generated in 0.600 seconds. --><!-- Cached page generated by WP-Super-Cache on 2010-08-13 09:44:32 -->
