SOAP XML Transform – NWS Forecast

The National Digital Forecast Database is a SOAP web service distributing U.S. forecast data via XML. I recently examined the output with an eye toward incorporating a basic forecast component into a webpage, but found it rather difficult to use directly. The purpose of this post is to share the process I used to transform the XML into an easier to use format.

An example of the format returned by my transformation is reproduced below.  To see an example of the original XML format returned by the service use the tool at http://graphical.weather.gov/xml/SOAP_server/ndfdSOAPByDay.htm.

 

The PHP code retrieving the original XML and returning the transformed version is reproduced below. A few notes are in order. First, you may note that E_NOTICE is suppressed. This is because it is possible that some elements may be empty and not return any data. Second, the xpath() method of the SimpleXML object returns an array of SimpleXML objects, of which we will generally want the 0th element. As a matter of convenience it is being retrieved via the list($someVar) construct. Finally, there is a lot of implicit casting going on as the xpath() method is cast to a string containing the element’s text.

 

At a high level, the code begins by matching the time-layout key from the <weather> element to the time-layout key of the corresponding <time-layout> element.  The key itself is parsed by the sscanf() function in line 18 to retrieve the number of elements to be processed.  Both elements are then iterated in lock-step by the for loop, generating the transformed XML.  Note that the same time-layout key matches the <conditions-icon> element and is also processed therein.

The <temperature> elements are processed in a similar manner, with the added feature of being mapped to the appropriate period in the new XML.  Note that the maximum and minimum types processed separately as they both have independent <time-layout> elements.

Hopefully, this code will be useful to others in transforming this rather unfriendly XML into a format more amenable to simple applications.

Leave a Reply

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

Time limit is exhausted. Please reload the CAPTCHA.