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

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.