Show the Current Temperature Using XML and PHP

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 said on November 8, 2008

    Thanks! This helped me a lot!

  2. Danny said on May 10, 2009

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

  3. Zac said on May 14, 2009

    Hi Danny,

    Check out: http://zacvineyard.com/blog/2009/05/14/parse-yahoo-weather-data-xml-with-php/

  4. Tom Lany said on 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!

  5. Zac said on 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().

  6. Jim said on 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!

  7. Zac said on December 5, 2009

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

Add Your Comment