How to Retrieve Yahoo! Weather using MagPie RSS and jQuery

Posted on December 10, 2008, under AJAX, JavaScript 

retrieve-yahoo-weather
In this tutorial I will show you how to display the Yahoo! Weather on your website, using a PHP RSS Parser, called Magpie RSS and JQuery (AJAX). The Weather RSS Feed uses 2 parameters: ‘p’ for location & ‘u’ for degree units. The base URL for the Weather RSS Feed is http://weather.yahooapis.com/forecastrss. An address that gets the weather forecast in Sunnyvale, CA (zip code: 94089) in Celsius (c) looks like this: http://weather.yahooapis.com/forecastrss?p=94089&u=c.

Let’s start creating the necessary files for this script by starting with the html file here the JavaScript and CSS code will be called!

index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
 <head>
  <title>Yahoo Weather!</title>
  <meta name="Keywords" content="ajax, weather, api, fetch, yahoo">

  <meta name="Description" content="yahoo, weather">

<script type="text/javascript" src="jquery-1.2.6.min.js"></script>

<link rel="stylesheet" type="text/css" href="style.css" />

<script type="text/javascript">
<!--
/*
Credits: Bit Repository
URL: http://www.bitrepository.com/web-programming/ajax/show-yahoo-weather.html
*/

$(document).ready(function(){

function get_weather()
{
var p = $("#code").val();

var u = ($('#u').attr('checked')) ? '&u=c' : '';
var to_load = 'get_weather.php?p='+ p + u;

$("#weather").show();

$("#weather").html('<img style="margin-top: 104px;" src="ajax-loader.gif" align="absmiddle">');

$("#weather").load(to_load);
}

// Trigger "get_weather" when the window loads
$(window).load(get_weather);

// Trigger "get_weather" when the form objects are used
$("#code").change(get_weather);
$("#u").click(get_weather);
});

//-->

</script>

</head>

 <body>
 <center>

<div align="center">

<h2 align="center">Yahoo! Weather</h2>

<form>
Get Weather for: <select id="code" name="code">
<option value="USCA1116">Sunnyvale</option>

<option value="USNY0996">New York City</option>
<option value="FRXX0076">Paris, France</option>
<option value="UKXX0085">London, United Kingdom</option>
<option value="UKXX0687">Buckingham, United Kingdom</option>

<option value="ASXX0001">Adelaide, Australia</option>
</select>

<input type="checkbox" id="u" name="u" value="c">&nbsp;with degrees Celsius and other metric units

</form>

<div id="weather"></div>
</div>
 </center>
 </body>
</html>

style.css

/* 
Credits: Bit Repository
CSS Library: http://www.bitrepository.com/
*/

html, body 
{
padding: 0;
border: 0px none;
font-size: 12px;
font-family: Verdana;
}

table
{
font-size: 12px;
font-family: Verdana;
}

/* Input */
input, select, checkbox
{
margin: 5 5 5 0;
padding: 2px; 

border: 1px solid #999999; 
border-top-color: #CCCCCC; 
border-left-color: #CCCCCC; 

color: #333333; 

font-size: 13px;
-moz-border-radius: 3px;
}

#weather
{ 
border: 1px solid #cccccc;
-moz-border-radius: 3px;

width: 500px;

padding: 5px;

height: 240px;
}

Let’s analyze the JS code! After $(document).ready() is called, the get_weather() function is created. It is used to pass the data from the form to get_weather.php using AJAX. This function is triggered when the page loads

$(window).load(get_weather);

and when either the select or checkbox form objects are used

$("#code, #u").change(get_weather);

.

We need to determine the value of the selected location from the form. Here’s the code that does this:

var p = $("#code").val();

Did the user choose to see the weather with degress Celsius and other metric units? We have to determine if he checked the checkbox:

var u = ($('#u').attr('checked')) ? '&u=c' : '';

What we will load?

var to_load = 'get_weather.php?p='+ p + u;

The parameters passed are ‘p’ (which is required) and u (if it’s requested). Using AJAX, a call is made to get_weather.php. Until the data is retrieved, an animated GIF loader is showing up:

$("#weather").html('');
$("#weather").load(to_load);

Here’s the content of get_weather.php, the file that connects to Yahoo! and gets the weather forecast:

<?php
error_reporting (E_ALL ^ E_NOTICE);

if(isSet($_GET['p'])) // at least 'p' is required
{
$p = $_GET['p'];

$u = isSet($_GET['u']) ? $_GET['u'] : '';

require('magpierss/rss_fetch.inc');

$url = 'http://weather.yahooapis.com/forecastrss?p='.$p.'&u='.$u;

$rss = fetch_rss($url);

$title = $rss->items[0]['title'];

$description = $rss->items[0]['description'];

echo "<br />".$title."<br /><br />".$description."<br />";
}
?>

yahoo-weather-magpie-rss-jquery

After we hide any notice errors using error_reporting (E_ALL ^ E_NOTICE);, we have to determine if the parameter ‘p’ is requested or not. If it is, we’ll check if the ‘u’ parameter was requested too and use we call the function fetch_rss() passing the $url to it. The function will return an array containing the data parsed from the RSS Feed. I chose to show ‘title’ and ‘description’:

$rss = fetch_rss($url);

$title = $rss->items[0]['title'];
$description = $rss->items[0]['description'];

echo "<br />".$title."<br /><br />".$description."<br />";

To see all the values of the array use the following code:

echo "<pre>"; print_r($rss); echo "</pre>";

If you need to find the codes for specific locations go to http://weather.yahoo.com/.

NOTE: The PHP Parser, MagPie RSS, caches the data retrieved from the feed. This is useful to load the data faster the next time you use the script. The default caching time is one hour (of course you can modify it). Consider checking the documentation files from the ‘magpierss’ folder (in the attached zip) for more information.

I hope that this tutorial gave you an idea of how to retrieve data from RSS using PHP & AJAX. If you have any comments regarding this article, please post them.

Happy coding ;-)

Comment via Facebook

comments

20 Replies to "How to Retrieve Yahoo! Weather using MagPie RSS and jQuery"

  1. Very helpful post.

    Any hints about how I can have a custom icon used in place of the Yahoo defaults?

    Thanks for the tutorial:)

    1. You can use the str_replace() function to replace the URL to the Yahoo Image with a URL to a custom image (in get_weather.php):

      Here's how you can replace the 'Cloudy' image:

      $description = str_replace('<img src="http://l.yimg.com/a/i/us/we/52/26.gif"/>', 
      '<img src="http://www.your-domain.com/path/to/cloudy-image.gif" />', $description);
      
  2. You rock. Is there a list of functions I can learn about within this api? How would I go about finding them? Many thanks for this:)

    1. Check the following addresses that should help you with what you need:

      YUI Library Examples: Connection Manager: Retrieving a Yahoo! Weather RSS Feed

      Yahoo! Weather RSS Feed

      Yahoo! Weather (useful if you need to find codes for specific locations)

  3. Nice article! We recently had to parse RSS feeds from mySpace using nothing more than jQuery and we found a slightly quicker solution – jFeed. I would definitely recommend checking it out. As for our widget, you’re all free to grab the sources to see how we tackled the problem:

    http://blarnee.com/wp/myspace-blog-reader-widget-using-jquery-ajax-and-greybox/

  4. Everything works fine in FF but in IE what is the problem??

  5. I solved it Thnxs, i download it again and works, maybe some file was missed or corrupted

  6. Now, the checkbox doesnt work in ie7 =(

    1. George,

      I’ve replaced

      $(“#code, #u”).change(get_weather);

      with

      $(“#code”).change(get_weather);
      $(“#u”).click(get_weather);

      Now it should work. Check the demo. I’ve tested it in IE8.

  7. How would I go about styling the text results? Furthermore placing custom hooks into the returned results so I can then style granularly with css?

  8. How would you use links rather that a drop down list to change the code var.
    just think it looks cleaner than a drop down list.

  9. How would I make it a textbox instead of a drop down – where user would then input the option value?

    Thanks

    1. @Alan Reddick and Eliot: Check the following URL address: http://www.bitrepository.com/demo/show-yahoo-weather/index2.html

      To see the changes, just view the source ;)

  10. hi. with regards to your coding, i have received an error. when i run it, the box which is suppose to display the weather details only came up with the follow:

    items[0]['description']; echo ”
    “.$title.”

    “.$description.”
    “; } ?>

    may i know what is the problem?

    1. Are you sure PHP is enabled on the host where you tested the application? You need to access the index.html in a web browser like this: http://your-domain.co/yahoo_weather/ or http://localhost/yahoo_weather/. I get the same result when I just open index.html by double clicking on it.

      1. @Gabriel,
        i am building my website on Visual Studio 2005 in visual basic. so in that case, how do i go about ensuring PHP is enabled? and which webpage should i run? or should i say how should i go about doing it?

  11. Hi is there a way to remove the :
    Full Forecast at Yahoo! Weather
    Many thanx

  12. Hello. I installed the script onto my PHP enabled server, however the preloader images displays but no weather results are shown. Is there anything I am missing? Do I need to set special permissions for any of the files? Thanks!

  13. can you please show me how to integrate US state and city and zip code? then display weahter atlest only form zip code or State

Leave a Reply


* = required fields

  (will not be published)


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Note: If you want to post CODE Snippets, please make them postable first!
(e.g. <br /> should be converted to &lt;br /&gt;)

POSTING RULES:

  • The comment must be relevant with the topic of the post.
  • Only comments with real email addresses will get approved. So, emails like 'abc@domain.com' will not be accepted.
  • Do not post the same message in multiple articles through the site.
  • Do not post advertisements, junk mail or pyramid schemes.
  • In case you post a link to another site, please explain briefly where the link goes as a courtesy to other users.
  • Do not post comments such as: "Thank you", "Awesome", "Nice tutorial", "Merci", etc.