<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	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/"
	>

<channel>
	<title>Carron Media &#187; Tutorials</title>
	<atom:link href="http://www.carronmedia.com/category/tutorials/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.carronmedia.com</link>
	<description>Web Design &#38; Development</description>
	<lastBuildDate>Wed, 15 Jun 2011 13:32:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<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; title: ; notranslate">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; title: ; notranslate">&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; title: ; notranslate">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; title: ; notranslate">
$(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; title: ; notranslate">
$.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; title: ; notranslate">
$(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; title: ; notranslate">
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; title: ; notranslate">
 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>
]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery-part-2/feed/</wfw:commentRss>
		<slash:comments>13</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; title: ; notranslate">&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; title: ; notranslate">&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; title: ; notranslate">&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; title: ; notranslate"> 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; title: ; notranslate"> 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; title: ; notranslate">document.getElementById('latest_tweet').innerHTML = statusHTML.join('');
</pre>
<p>and in its place type:</p>
<pre class="brush: jscript; title: ; notranslate">$('.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; title: ; notranslate">$(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>
]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/display-your-latest-twitter-update-with-jquery/feed/</wfw:commentRss>
		<slash:comments>32</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; title: ; notranslate">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; title: ; notranslate">&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; title: ; notranslate">&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; title: ; notranslate">        $('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; title: ; notranslate">            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; title: ; notranslate">            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; title: ; notranslate">&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>
]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/extend-google-analytics-with-jquery/feed/</wfw:commentRss>
		<slash:comments>45</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 &#8216;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; title: ; notranslate">&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; title: ; notranslate">&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; title: ; notranslate">    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; title: ; notranslate">    $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; title: ; notranslate">&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; title: ; notranslate">&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>
]]></content:encoded>
			<wfw:commentRss>http://www.carronmedia.com/create-an-rss-feed-with-php/feed/</wfw:commentRss>
		<slash:comments>77</slash:comments>
		</item>
	</channel>
</rss>

