Twitter
RSS

Show the Current Temperature Using XML and PHP

November 7, 2008 - 7 Comments Bookmark and Share

Many times it is neat to display the current temperature on your website, and there are a lot of different ways to go about this. I’d like to show you the easiest way to display the temperature on your site using XML from the National Weather Service (NOAA) and simple XML commands in PHP.

Get Started

To get started, you will need to find weather data. The National Weather Service offers this data in free XML feeds, which you can find at http://www.weather.gov/xml/current_obs/. To get started, select an XML feed you’d like to use. I’m using a Boise, ID feed, which looks like:

http://www.weather.gov/xml/current_obs/KBOI.xml

You will is this URL in the PHP code to get your location’s current temperature.

The Code

To get the data we want from the XML feed, we will be using the simplexml_load_file() function. This will, essentially, parse the XML for us, making it ready to use as text online. Here is the code you will need:

<?php
 
// Load the XML
$xml_boise = simplexml_load_file('http://www.weather.gov/xml/current_obs/KBOI.xml');
 
// Get Current Boise Temperature
$boise = $xml_boise-&gt;temp_f;
echo $boise  . "&amp;#176;";
 
?>

This is way too easy, if you ask me. The output you get should be something similar to 64°.

Download the Source Code

Comments

  1. Blake(November 8, 2008)

    Thanks! This helped me a lot!

  2. Danny(May 10, 2009)

    This is useful, but what if I want to use a dynamic user-submitted zip code?

  3. Tom Lany(September 18, 2009)

    This is totally awesome! I have been searching for hours for something that parses weather like this.

    Just wondering, is there a way to cache this information easily?

    Thanks again!

  4. Zac(September 18, 2009)

    Hey Tom,

    I just cache the result in a text file using PHP. Not too hard. Check out PHP’s fopen() and fwrite().

  5. Jim(December 5, 2009)

    Hi,

    Nice article. However, your download link is throwing a 404 error. I was hoping to download the source code, so having the download not work is sort of a bummer!

  6. Zac(December 5, 2009)

    Hi Jim, Thank you for pointing out that my download link was broken. It is now fixed.

Leave a Reply