Really simple Really Simple Syndication syndication

June 7th, 2007. Tagged: php

Nice title, eh?

OK, so all of a sudden theweathernetwork.com buttons I was using to show the weather in Sofia, Bulgaria and selected Canadian cities on the community site bgcanada.com, stopped working. Reason: unknown. So it was time for a change, since those buttons were generated by some javascripts, hosted by theweathernetwork, which is kind of a web 1.0 way of sharing content. In the days of APIs and stuff, this is a shame.

The first substitute that came to mind to check were the Yahoo APIs and feeds and, no surprise, they do offer weather feeds. All you need is the code of the city you're interested in (or zip code for the States) and you're good to go. I also wanted the temperatures to be displayed in Celsius, and there was indeed an option to set this. The feed URL for Montreal for example looks like:

http://weather.yahooapis.com/forecastrss?p=CAXX0301&u=c

With a little searching on the real Yahoo weather site, I was able to figure out the codes of the cities I'm interested in. From there it was a breeze.

Here's the script that takes an array of cities and produces a single HTML page with the weather information. It's using simplexml_load_file(), which makes things so simple, it's scary.

<?php
// array of cities we're interested in
// the codes are taken from weather.yahoo.com URLs
// by searching for the city
$cities = array(
    'Sofia'     => 'BUXX0005',
    'Montreal'  => 'CAXX0301',
    'Toronto'   => 'CAXX0504',
    'Vancouver' => 'CAXX0518',
    'Ottawa'    => 'CAXX0343',
);
 
// general purpose feed URL with placeholder for city code
$feed = 'http://weather.yahooapis.com/forecastrss?p=%s&u=c';
 
// loops cities
foreach ($cities AS $name => $code) {
 
    // load XML from the real feed URL
    $url = sprintf($feed, $code);
    $res = @simplexml_load_file($url);
 
    // on success, spit out city name and weather data
    if ($res) {
        $data = $res->channel->item->description;
        echo '<h2>', $name, '</h2>', $data;
    }
}
?>

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov