How to Retrieve Yahoo! Weather using MagPie RSS and jQuery

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 Comments

  1. kayala says

    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

  2. Chris says

    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!

  3. Dave says

    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?

  4. Eliot says

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

    Thanks

  5. Alan Reddick says

    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.

  6. Josh says

    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?

    • GabrielGabriel says

      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. Josh says

    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:)

  8. josh says

    Very helpful post.

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

    Thanks for the tutorial:)

    • GabrielGabriel says

      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);
      

Leave a Reply

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