More code snippets!
October 27, 2008If you’ve done any Googling about weather data then it should be clear that the National Weather Service provides one of the largest and most comprehensive sources of weather data.
This posting is to discuss the Current Conditions page on the NWS website and in particular the XML formatted data that is available. As I’m sure you know, one of the advantages of XML is that is strongly structures data so that there is no doubt what each element specifically is. To process XML in any language it’s always best to use inbuilt code or existing library extensions that will parse the XML data allowing you to extract just the information you require. For this example we’ll use PHP (specifically version 5) as it’s a very popular language….
So, we’ll start with working out which site we require weather data for. On the NWS page there is a link to a large zip file that covers all known weather data sites… it’s worth downloading that now.
Unfortunately you’ll just end up with approx 2800 files with obscure four character names! These are known as ICAO codes (International Civil Aviation Organization) and you’ll need to check around on the internet for a site that allows you to match a code to a particular site. For example, the Airline Industry Update site has a handy facility (as of November 2008) that allows you to match a code with a location.
So, now you should have worked out which locations you’re interested in current observations for. Let’s choose KJFK – Kennedy International Airport in New York.
Next we can see from the website that the correct xml address for each of the weather data sites looks like…
http://www.weather.gov/xml/current_obs/XXXX.xml
Of course, where XXXX is the 4 letter ICAO code! So to retrieve the current observations for JFK we’d use the following address…
http://www.weather.gov/xml/current_obs/KJFK.xml
Now if you load that into a browser you get a wealth of weather data… but not in an easily readable format. Next we need to create an XML object in our PHP application like this…
$webAddress = 'http://www.nws.noaa.gov/data/current_obs/KJFK.xml';
$xmlResults = simplexml_load_file($webAddress);
If this works, you’ll end up with a new variable called $xmlResults that you can now extract key pieces of information for. Let’s look at a couple of examples…
echo $xmlResults->weather, ' : Current Weather Summary';
echo '<br>';
echo $xmlResults->temperature_string, ' : Current Temperature Information';
echo '<br>';
echo $xmlResults->wind_string, ' : Wind Information';
echo '<br>';
Pretty great!






