![]()
Feeds 101
Oct 27th in Other by SiddharthFeeds. RSS. Atom. Syndication. Subscribers. These are some of the keywords floating around the web and have gained notorious prominence over the years. In this guide, we'll take a look at a number of things including what feeds are, why you need to have a feed for your site, how to set up one and then publish it.
![]()
Author: Siddharth
Hi! I am Siddharth, a web developer/ designer based in Chennai with expertise in C#, Python, CSS and JavaScript . I resort to using jQuery when I don't feel like writing raw JS. I am passionate about web technologies and video games and I really think code *is* art. You can follow me if you want.
What are Feeds?
In this digital age, users no longer have the luxury of time to check for new content manually each time or more importantly remember each site they want to get information from. Web feeds, news feeds or feeds helps the user simplify this process drastically.
Feeds, to put it simply, are a way to publish frequently updated content. Your feed is a XML formatted document which lets you share content with other users on the web. Users, subscribers in this lingo, can use your feed to read updated information on your site if and when it is posted.
Why you Should Publish Feeds
From a web developer's perspective, one of the main reason for publishing a feed is user convenience. With a feed for users to subscribe to, they don't have to check for new content manually each time. They can just subscribe to your feed and get notified new content is posted. No hassles! If you fear you'll lose your advertisement revenues in this process, you can just as easily include ads in the feed.
Publishing a feed also means that it is easier for third party content providers to syndicate your content thus gaining more exposure and traffic in the process.
Feed Formats
As with any hot technology, there are a few well established, competing protocols for creating web feeds.
RSS
RSS is the dominant format for publishing web feeds and stands for Really Simple Syndication. RSS has a number of variants each branching out from RSS 1.x and RSS 2.x versions. A lot of services, including WordPress use RSS for creating its feeds.
Despite it's massive user base, RSS does suffer from some drawbacks, some significant, the most important one being its inability to handle HTML. Nevertheless, we'll be creating our feed today in the RSS format.
Atom
Atom was created in order to mitigate a lot of RSS' drawbacks including the ability to include properly formatted XML or XHTML in your feeds. But since RSS has almost become synonymous with feeds, Atom has always been the much more feature rich and flexible little brother.
RSS's Format
In the interest of keeping it simple, we'll just stick with RSS today instead of trying out each format out there.
Each and every RSS feed out there follows this general format:
Defining the version and encoding
RSS is a subset of XML which means we need to make sure it is marked so appropriately.
- <?xml version="1.0" encoding="utf-8"?>
- <rss version="2.0">
- ..
- </rss>
The first line is the XML declaration. We define the version so that it validates correctly as XML. The encoding part is purely optional.
The second line defines the version of RSS we are going to use today. We are going to use RSS 2 today.
Each feed need to be inside a channel so that goes inside the markup. Thus far our feed looks like so.
- <?xml version="1.0" encoding="utf-8"?>
- <rss version="2.0">
- <channel>
- ..
- </channel>
- </rss>
Filling in the feed's source information
This is where you fill in all the important details like the name of the feed, the URL and a description of the site.
- <title>My feed</title>
- <link>http://www.somesite.com</link>
- <description>Random ravings :)</description>
You aren't limited to these fields alone. There are a number of other optional fields including the language of your feed, an image for the logo, when the feed was updated last and many more.
Adding the content
Each item in the feed has to be enclosed by an <item> element. An item can be anything: a news post, a status update, new products: anything. Each item requires a title and a corresponding link. As with before, you can make use of a number of optional elements including description and author fields.
A sample item would look like so:
- <item>
- <title>Feeds 101</title>
- <link>http://www.net.tutsplus.com</link>
- <description>Let's create an RSS feed from scratch!</description>
- <author>Siddharth</author>
- </item>
Building a Static RSS Feed
Now that we know all the individual parts of a RSS file and how they all gel together, it's time to see a complete RSS file.
- <?xml version="1.0" encoding="utf-8"?>
- <rss version="2.0">
- <channel>
- <title>My feed</title>
- <link>http://www.somesite.com</link>
- <description>Random ravings :)</description>
- <item>
- <title>Feeds 101</title>
- <link>http://www.net.tutsplus.com</link>
- <description>Let's create an RSS feed from scratch!</description>
- <author>sid@ssiddharth.com</author>
- </item>
- </channel>
- </rss>
It may not look like much but gents, this is a working RSS feed. We've defined everything that needs to be defined and if you are inclined to do so, you can put this on the web.
Building a Dynamic RSS Feed
Happy about building your first RSS feed? You should be! But the problem with this is that the feed is completely static: something which is completely counter intuitive as compared to the concept of feeds. We'll rectify this now by building a simple PHP script that mooches off data from a database and updates the RSS feed when needed.
Since I like having pretty URLs, I am going to name this file index.php and place it in a folder called feed so my feed can be accessed at www.mysite.com/feed
For the sake of simplicity, I am going to assume you already have a database containing your articles. I am also assuming the database has columns named title>, link, description and date in a table called posts.
Building the base
- <?xml version="1.0" encoding="utf-8"?>
- <rss version="2.0">
- <channel>
- <title>My feed</title>
- <link>http://www.somesite.com</link>
- <description>Random ravings :)</description>
- <?php
- // Code here
- ?>
- </channel>
- </rss>
Since the XML declarations and feed information are going to be pretty static, we'll keep them static. You'd want to keep them dynamic if you were writing a PHP class for generating RSS feeds but for our purposes, this should do.
Defining database information and connecting
- DEFINE ('DB_USER', 'some_username');
- DEFINE ('DB_PASSWORD', 'some_unusually_weak_password');
- DEFINE ('DB_HOST', 'localhost');
- DEFINE ('DB_NAME', 'database');
Simple as it looks. We just note down a bunch of information for use later.
- $connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or
- die('Connection to the specified database couldn't be established');
- mysql_select_db(DB_NAME) or
- die ('Specified database couldn't be selected');
Pretty generic connection code. We try to connect using the credentials noted earlier. If nothing hitches up, we select the relevant database for use later.
Querying the database
- $query = "SELECT * FROM posts ORDER BY date DESC";
- $result = mysql_query($query) or die ("Query couldn't be executed");
This isn't really a SQL oriented tutorial and so I'll skim over it. We just grab all the posts from the table so that we can add it to the feed. Nothing else fancy going on over there.
Populating the items list
- while ($row = mysql_fetch_array($result, MYSQL_ASSOC) {
- echo '<item>
- <title>'.$row['title'].'</title>
- <link>'.$row['link'].'</link>
- <description>'.$row['description'].'</description>
- </item>';
- }
We grab each individual record and then print it inside the relevant element to create the items list. Note that since I wanted a hash to work with I set the result type to MYSQL_ASSOC.
And with that the PHP part is done. The complete code should look like below.
- <?php
- header("Content-Type: application/rss+xml; charset=utf-8");
- ?>
- <?xml version="1.0" encoding="utf-8"?>
- <rss version="2.0">
- <channel>
- <title>My feed</title>
- <link>http://www.somesite.com</link>
- <description>Random ravings :)</description>
- <?php
- DEFINE ('DB_USER', 'some_username');
- DEFINE ('DB_PASSWORD', 'some_unusually_weak_password');
- DEFINE ('DB_HOST', 'localhost');
- DEFINE ('DB_NAME', 'database');
- $connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or
- die('Connection to the specified database couldn't be established');
- mysql_select_db(DB_NAME) or
- die ('Specified database couldn't be selected');
- $query = "SELECT * FROM posts ORDER BY date DESC";
- $result = mysql_query($query) or die ("Query couldn't be executed");
- while ($row = mysql_fetch_array($result, MYSQL_ASSOC) {
- echo '<item>
- <title>'.$row['title'].'</title>
- <link>'.$row['link'].'</link>
- <description>'.$row['description'].'</description>
- </item>';
- }
- ?>
- </channel>
- </rss>
You should now be able to access your feed at www.yoursite.com/feed.
>Validate your Feed
Just like with xHTML, RSS/XML needs to be well-formed and without errors. There are a number of validators to help you with this. Here are some of my often used ones.
Since RSS can only handle escaped HTML, make sure you use < lt; for < and < gt; for > respectively. Also make sure you replace special characters to their respective HTML codes. Forgetting to do so will probably result in invalid markup and break the feed.
All Done! Publish that Feed
Now that we've created the feed and made sure it validates, we can now go publish it. You can use a service like Feedburner to manage your feeds. This lets you glean a lot of information including how many subscribers you have. Or you can take the easy way out and just link to your feed on your site.
Have you ever noticed the feed icon on your browser lighting up for certain pages alone? This means the browser has been notified that a feed of the current page is available for subscription. In order for the user's browser to automatically detect the feed's presence you need to add this small snippet to the head section of your page:
- <link rel="alternate" type="application/rss+xml" title="Article RSS Feed"
- href="http://www.yoursite.com/feed" />
You need not limit yourself to one feed. You may have a feed for each author or a feed for each category of the products you sell. Feel free to add as many feeds you want to the head section.
Conclusion
And that brings us to an end to this joy ride. We've gone over what feeds are, what purpose they serve and the different formats available. Next we looked at RSS, its skeleton structure and then learned how to create a simple dynamic RSS feed. Hopefully you've found this tutorial interesting and this has been useful to you.
Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web.
Comments [1]
This article illustrates some useful basic concepts that explain how it’s easy interacting with HTML forms using jQuery. I’ve prepared five practical step-by-step examples you can follow to learn quickly this argument.
For a printable reference guide to the jQuery API I suggest you to download my jQuery Visual Cheat Sheet or take a look at the official jQuery documentation.
Simple characters counter
The first example is a simple character counter. Here is the result (try to write something into the input field below):
0How can you implement it? Add an input field in your HTML document and a
<span>tag for the counter in this way:<input type="text" id="input-text"/><span id="count"></span>Then add this JavaScript code into the
<head>tag of your page or into an external JavaScript file:$(document).ready(function() { $("input[id='input-text']").keyup(function count(){ counter = $("input[id='input-text']").val().length; $("#count").html(counter); }); });The previous script, on
keyupevent, gets the value and the length of the string contained into the input field withID="input-text"and updates the DOM element withID="count"(in this case the<span>tag) using the jQuery attributehtml().Characters countdown
Now we can try to implement a simple variant of the previous example to realize a script that displays the number of remaining available characters in an input field. Here is the result (try to write something into the input field below):
10 remaining charsThe HTML code is exactly the same of the previous example. I only changed the
idproperty for theinputandspantags.<input type="text" id="input-text-2"/> <span id="count-2"></span>Here is the JavaScript code that updates the counter:
$("input[id='input-text-2']").keyup(function countRemainingChars(){ maxchars = 10; counter = $("input[id='input-text-2']").val().length; if(counter==0){ $("#count-2").html(0 +" remaining chars") } else { $("#count-2").html(maxchars-counter+" remaining chars"); } });In the code above I declared the variable
maxcharto set the maximum number of allowed characters for the input field withid="input-text-2". Onkeyupevent, the script gets the value and the length of the string contained into the input field withid="input-text-2"and updates the DOM element withID="count-2” (in this case the<span>tag) with the difference betweenmaxchars-counteror0.Basic form validation
This example illustrates how to implement a simple form validation. When the input element loses focus, an error message appears if the field is empty. Here is the result (try to select the input field and leave it blank):
Here is the HTML code:
<input type="text" id="input-text-3" maxlength="10" /><span id="msg"></span>And here is the JavaScript code:
$("input[id='input-text-3']").blur(function validate(){ el = $("input[id='input-text-3']"); inputString = el.val(); if(inputString==""){ el.css({ "background" : "red", "color" : "white" }); $("#msg").html("This field can't be empty!"); } else { el.css({ "background" : "white", "color" : "black", }); } });On
blurevent (when the input field loses focus), an error message appears if the field is empty and the background and text color of the input field change to red and white.Pick values from a list
This example illustrates how it’s easy to add values into an input field picking them from a list. Here is the result (click on a list element, Smashing Magazine, Woork Up or Mashable):
Click on a website from the list:
- Smashing Magazine
- Woork Up
- Mashable
The HTML code to implement this example is not complex: I added an unordered list that contains the list of values you can pick:
<input type="text" id="input-text-4" size="40"/> <ul id="values"> <li>Smashing Magazine</li> <li>Woork Up</li> <li>Mashable</li> </ul>And here is the JavaScript code:
$("ul[id='values'] li").click(function suggestValues(){ input = $("input[id='input-text-4']"); el = $(this).html(); $(this).remove(); newinput = input.val(); newinput = (newinput + el + ", "); input.val(newinput); });Naturally, this is a very basic example you can improve and customize how you prefer for your specific needs in your web projects.
Add elements into a list from a select field
This example illustrates how to add some value into an external list piking them from a
selectelement. When you add a new element into the list, the selected option is contextually removed from theselectelement. I also added a nicefadeInanimation to improve the final effect.
Here is the HTML code:
<select id="my-list"> <option value="1">Smashing Magazine</option> <option value="2">Woork Up</option> <option value="3">Mashable</option> </select> <input type="button" id="submit-list" value="Button"/> <ul id="selected-items-list"></ul>And here is the JavaScript code:
$("#submit-list").click(function selectItem(){ s = $("option:selected") el = s.text(); destination = $("#selected-items-list"); $(destination).append('<li>'+el+'</li>'); $(destination +':last').css('display', 'none').fadeIn(1000); $("option:selected").remove(); if($('#my-list option').length==0){ $('input[id=submit-list]').attr('disabled', 'disabled'); } });When you pick an option from the
selectelement, the option it’s added into the destination list withid=selected-items-listusing.append(). To remove the option for theselectelement you can use.remove(). When theselectis empty you can disable the button using.attr().Conclusions
In this post we’ve started learning how to use jQuery to interact with HTML forms. Obviously all concepts illustrated are very simple but easy to learn and useful to start using quickly jQuery. If you are a developer I suggest you to download my jQuery 1.3 Visual Cheat Sheet. Comments and suggestions are appreciated.
Comments [0]
By Henry Jones10 Fresh jQuery Tutorials to Enhance Navigation Menus
Make sure you read this popular related article.
13 Super Useful jQuery Content Slider Scripts and TutorialsA few years ago, when designers wanted to add cool effects to the navigation of a website they used Flash. We all know the types of problems that caused. Now with the growing popularity of javascript frameworks like jQuery, those same types of “Flash-like” effects can be achieved without Flash. Here are 10 jQuery tutorials and techniques to enhance your website’s navigation and menus.
Horizontal Scroll Menu with jQuery Tutorial
BBC Radio 1 Zoom Tabs
Spritemenu
Outside the Box Navigation with jQuery
Sexy Drop Down Menu w/ jQuery & CSS
A Simple and Beautiful jQuery Accordion Tutorial
Make a Mega Drop-Down Menu with jQuery
jQuery look: Tim Van Damme
jQuery Feed Menus
Create a Good Looking Floating Menu with jQuery Easing
Related Posts
Here's some other articles that you will definitely find useful.
13 Super Useful jQuery Content Slider Scripts and Tutorials
14 Easy to Implement Drop Down Menu Solutions
Create a Resizable Image Grid with jQuery
15 Excellent jQuery Navigation Techniques and Solutions
11 Excellent Solutions for Creating Tooltips
Digg | Stumble | Del.icio.us Subscribe to RSSIf you enjoyed this article, consider sharing it on one of the following social bookmarking site.
Comments [0]
Becoming a Font Embedding Master
I've spent a couple days worth now trying to figure out the best and most complete approach to font embedding using
@font-face. It really is a dark art that must be mastered. It is by no means a straightforward process.Font Formats
Generally speaking, these days, a font on our system is going to be one of two formats: TrueType (with a .ttf file extension) or OpenType (with a .otf file extension). While it would be nice to be able to just throw a font like this on the web and link it up, we're hit with two major limitations.
- Licensing, and
- Browser Support
Licensing
Licensing is one of the biggest hurdles. It can be difficult to find a font that really works within the overall aesthetic of a design. It's the reason we've had to resort to exporting images, sIFR or Cufon.
Even many free fonts have limitations on how they can be used, often times requiring specific directions on linking back to the original source or only using them in non-commercial sites.
These days, a number of resources are popping up—especially those dedicated to font embedding. A good start to finding the right font for your project would be Font Squirrel. Font Squirrel even provides
@font-facekits to make implementation on your web site easy. However, even these kits don't provide as complete of browser support as what I'm covering here.Browser Support
Which leads me into the other major issue, browser support. Font embedding with a TrueType or OpenType font only works as of Firefox 3.5, Safari 3.1, and Opera 10. (You can enable it in your copy of Chrome 2 by using a command line switch.)
Okay, that's decent already but we can do better. We can get Internet Explorer 4+, Chrome 0.3+, Opera 9+ and even a little mobile Safari action.
EOT
Internet Explorer supports a particular type of format called Embedded OpenType that provides some control over where and how the font is allowed to be embedded. You'll need to convert your TTF into an EOT format. Microsoft provides a tool called WEFT but it is ancient and I'll be damned if I can get it working. Thankfully, there is a command line tool called TTF2EOT that can convert your font.
If you have an OTF file, you'll need to convert it into a TTF file before you can convert it into an EOT. FontForge is the application that I use to do it and has provided me with the most consistent results. I urge you to check out my screencast on OTF to TTF conversion using FontForge as it is a surprisingly tricky process.
As you'll soon see, having the file in a TTF format will help us with the next step.
SVG
With TTF/OTF and EOT, we have decent browser coverage but the coup de grace is to add one more font format to the mix: SVG. SVG fonts are supported by Chrome 0.3+ without having to use a command line hack, along with Opera 9 and (with testing provided by the Twitter folk) iPhone OS 3.1. Additional mobile browsers may support it as well but I have been unable to get thorough confirmation on this.
FontForge has an option to export to an SVG format but I was seeing odd behaviour in Opera with missing characters. Alternatively (and thankfully!), I found a Java application that can be run from the command line called Batik. When running the conversion, you must specify the ID parameter. You won't get an error if you don't but the ID is important at the CSS stage.
java -jar batik-ttf2svg.jar ./MuseoSans-500.ttf -o museo.svg -id museoOne of the concerns in exporting to SVG is file size. Immediately I had noticed that my 29k font was now sitting in well over 100k. The biggest reason was the number of
hkernelements that, I guess, are meant for kerning. (I'm smart like that.) However, you should be able to delete them without greatly impacting the display of your font but greatly impacting the file size. The other thing I noticed wasglyph-name="null"on all of the glyph nodes. I was able to remove them with, once again, no impact to the display of the font. Having done so brought my SVG fonts to the point where they were smaller than the original TrueType font I had converted from (29k to 20k in one case and 18k to 12k in another case).CSS
Now that we have our three files—TTF (or OTF), EOT and SVG—it is time to get our CSS mojo on. Starting with Paul Irish's bullet-proof base, I've added an additional entry for the SVG font.
@font-face { font-family: 'GothicCustom'; src: url("LeagueGothic.eot"); src: local('League Gothic'), url("LeagueGothic.svg#lg") format('svg'), url("LeagueGothic.otf") format('opentype'); }The
font-familyname that you specify here is arbitrary and I like to choose a unique name to make it clear in my other declarations that I'm using an embedded font.The SVG syntax has one particular thing of note, and that is the ID anchor after the font name. Specify the ID that you used when doing the SVG conversion. Alternatively, open up the SVG font and make sure that the font element has an ID.
<font id="lg">Specifying
font-familyworks as it normally would. Just specify the font name that you used in your@font-facedeclaration.font-family: 'GothicCustom', 'Arial Narrow', sans-serif;Subsetting
In the screencast, I gave a quick demo of how to subset a font by clearing glyphs that aren't to be used in the final font. Why would you want to subset a font? It makes the file smaller. Some font files can easily weigh in at 200k. That's a lot to download when people don't need to. For example, the masthead on this site is—as of this writing—using Museo Sans. A great font that weighs in at around 65k. Since the masthead only uses a limited set of characters, I was able to remove anything I didn't need and brought the file size down to 20k.
If you optimize your images, why not optimize your fonts?
Text Transform Bug
There is one caveat to be aware of when subsetting. In my case, I assumed that I could quickly do without most of the lowercase glyphs. A
text-transform:uppercasestatement was all I really needed.<div>About</div> div { text-transform:uppercase; }This works fine in Firefox and Safari but Opera and Internet Explorer both seem to decide whether to use a font for a particular character by looking at the lowercase character first. This meant it was using the uppercase characters from a fallback font. That's certainly less than ideal.
Of course, you can always just change the HTML source to be uppercase, if you were dead set on removing those glyphs.
Print Style Sheets
When I first set out to use
@font-face, I didn't even foresee this added bonus: the custom fonts also work just fine with print style sheets. It wasn't like using image replacement techniques and having to fall back to a boring browser font for print. It felt good printing off a page of my site that still used the same fonts as what I saw on screen.Never Going Back
Despite the frustration, I've come to the conclusion that—if the design called for it—I'd rely on
@font-faceover sIFR and Cufon. I really prefer not having to use JavaScript and I enjoy all the other benefits that come from using@font-face. I certainly look forward to the future when all of these headaches are no longer necessary.
Comments [0]
Comments [0]