Showing the current weather on your website using MagpieRSS

The idea

I recently completed a quick project where the client wanted to have the local weather conditions displayed on his website through an RSS feed. The first hurdle I came to was finding a website that provided the feed and allowed for its use on other sites. I originally tried weather.com, but their terms of service didn’t allow commercial use. After searching for a while I came across weather.gov which provides XML and RSS feeds of the current weather conditions and allows you to display them on your own website without restrictions. The only downside is that you probably won’t be able to show weather for your exact location (only from the nearest observation center). You can view locations by state at this page.

Installing MagpieRSS

It’s easy to get started with MagpieRSS. Download it from SourceForge.net and extract it. Next, copy the extlib folder and the files: rss_cache.inc, rss_fetch.inc, rss_parse.inc, and rss_utils.inc into your website’s includes directory, preferably outside the web root. Next we need to set up the PHP that uses MagpieRSS to parse the RSS feed.

//include the rss_fetch file
require('rss_fetch.inc');

//set up a variable that we will use in displaying the feed's information
$rss = fetch_rss("http://www.weather.gov/xml/current_obs/KEOK.rss");

The $rss variable is an array of values from the feed including the title, link back to weather.gov for more details, and description. In most feeds we would have multiple items in the feed that we would want to loop through and display. This feed; however, only returns one item – and that is all we want to display. So when we call the item we insert [0] to specify the first array value.

//since this is set up as an array that could have multiple values we need to specify the first value in the array with [0]
<p id="title-link"><strong><a href="<?php echo $rss->items[0]['link'];?>><?php echo $rss->items[0]['title'];?></a></strong></p>
<p id="description"> echo $rss->items[0]['description'];</p>

Now that we have the format for our code we can save this file as feeder.php and put it in our includes directory. Next, we include it in our website like this:

include "includes/feeder.php";

Last, we give it a little bit of style:

#weather {
    text-align:center;
    border:1px solid #a29d7c;
    background-color:#d4d2c3;
    width:20em;
    margin:.5em;
    float:right;
}

#weather p{
    font-size:90%;
}

#weather p#description {
    margin-top:0;
    margin-bottom:35px;
    text-align:left;
    padding-left:4px;
}

#weather img {
    margin:4px;
    border:1px solid #a29d7c;
}

#weather .tag {
    clear:both;
    font-size:8pt;
}

I hope you find this useful. Feel free to view the source and use it in your own website.

Leave a Reply

Your email address will not be published. Required fields are marked *