Code covered by the BSD License  

Highlights from
Weather.gov U.S. Current Weather Conditions

from Weather.gov U.S. Current Weather Conditions by Skynet
Get U.S. location specific current weather data from Weather.gov.

wgovcwc.m
function[data]=wgovcwc(sid)

%WGOVCWC Get U.S. location specific current weather data from Weather.gov.
%
% WGOVCWC(SID) queries the XML Feeds of Current Weather Conditions as
% provided by NOAA's National Weather Service (http://www.weather.gov), and
% returns a struct containing current weather conditions for the area
% specified by the corresponding four char SID(s) (Station ID(s)).
%
% Data is available only for a limited number (about 1,800) of locations
% across the United States and U.S. Territories. To determine the four char
% Station ID(s) of the relevant location(s) and for more information, visit
% http://www.weather.gov/data/current_obs/.
%
% The input argument SID can be a single Station ID, or a char or cell
% array of Station IDs.
%
% Data is acquired in XML format, after which it is converted into a struct
% using the xml_parse function. This function is available in the XML
% Toolbox by Marc Molinari on the MATLAB Central File Exchange (File ID 
% 4278). The URL to it is:
%   http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=4278&objectType=file
%
% EXAMPLES:
%
%   Example 1: Using a single SID.
%   wgovcwc('KNYC') returns a 1x1 struct containing fields (among others):
%
%              location: 'New York City, Central Park, NY'
%      observation_time: 'Last Updated on Mar 13, 5:51 pm EST'
%               weather: 'Fair with Haze'
%                temp_f: 57
%     relative_humidity: 78
%
%   Example 2: Using a char array of three SIDS.
%   wgovcwc(['KNYC';'KJFK';'KHPN']) returns a 3x1 struct.
%
%   Example 3: Using a cell array of three SIDs.
%   wgovcwc({'KNYC';'KJFK';'KHPN'}) returns a 3x1 struct.
%
% REMARKS:
%
%   - The weather data is not updated continuously or even every few
%     minutes, and this function does not include any caching features, so
%     conservative use of the service, perhaps no more than once per hour
%     per location, is warranted. Refer to the corresponding
%     'suggested_pickup' and 'suggested_pickup_period' field values.
%   - As the XML feed layout is updated by the NWC over time, the layout of
%     the output struct should automatically be correspondingly updated.
%     Unexpected changes to the feed may however prevent this function from
%     working predictably.
%   - This function has been tested with version 2005-04-20 of the XML
%     Toolbox.
% 
% VERSION: 20060318
% MATLAB VERSION: 7.3.0.267 (R2006b)
%
% See also URLREAD, CELLFUN, STRUCTFUN.

%{
VERSION HISTORY:
20070108: - Removed extra line breaks.
          - Added hyperlinks to relevant error messages.
20060318: - Added implicit support for char and cell array inputs.
20060317: - Increased clarity and specificity of error messages.
          - Made minor updates to help.
20060316: - Updated subfunction to allow nested str2double conversion.
20060315: - Added an example on using a char array as the input argument.
20060314: - Disabled unnecessary warning while using xml_parse.
20060313: - Original version.

KEYWORDS:
atmosphere, climate, meteorology, NOAA, NWC, temperature, weather
%}

%**************************************************************************

%% Call main subfunction as relevant

err_msg='The input is invalid.';

if ischar(sid)
    if size(sid,1)==1
        data=wgovcwc_main(sid);
    elseif size(sid,1)>1
        data=cellfun(@wgovcwc_main,cellstr(sid));
    else
        error(err_msg)
    end
elseif iscell(sid)
    data=cellfun(@wgovcwc_main,sid);
else
    error(err_msg)
end

%**************************************************************************

%% Main subfunction

function[data]=wgovcwc_main(sid)

%% Declare URL

url=['http://www.weather.gov/data/current_obs/',sid,'.xml'];

%% Resiliently read URL

tries_max=3;
wait_time_base=.75;

for tries=1:tries_max;
    [data,status]=urlread(url);
    if status==1
        break
    end
    if tries==tries_max
        error(['The URL ''<a href="',url,'">',url,'</a>'' could not be',...
               ' accessed. Ensure that the Internet connection is acti',...
               've, that the Station ID ''',upper(sid),''' is valid, a',...
               'nd then retry.'])
    end
    pause(tries*wait_time_base)
end
clear url tries* status wait_time_base 

%% Partly confirm validity of data

if isempty(strfind(data,['<station_id>',upper(sid),'</station_id>']))
    error(['''',upper(sid),''' does not seem to be a valid Station ID.',...
           ' Ensure that a valid Station ID is used, and retry.'])
end

%% Confirm presence of xml_parse function

% This cell can optionally be commented

if isempty(which('xml_parse'))
    fe.url='http://www.mathworks.com/matlabcentral/fileexchange/';
    fe.xt.url=[fe.url,'loadFile.do?objectId=4278&objectType=file'];
    error(['The function xml_parse is not available. Ensure that the <',...
           'a href="',fe.xt.url,'">XML Toolbox</a> by Marc Molinari, a',...
           'vailable on the <a href="',fe.url,'">MATLAB Central File E',...
           'xchange</a>, is installed. The URL to it is <a href="',...
           fe.xt.url,'">',fe.xt.url,'</a>.'])
end

%% Parse XML to struct

wstate=warning('off','all');
data=xml_parse(data);
warning(wstate);
clear wstate

%% Convert numbers from strings to doubles

% This cell can optionally be commented

data=structfun(@cnsd,data,'UniformOutput',false);

%**************************************************************************

%% Subfunction to convert numbers from strings to doubles

function[field]=cnsd(field)

if ischar(field) && ~isnan(str2double(field))
    field=str2double(field);
elseif isstruct(field)
    for i=1:numel(field)
        field(i)=structfun(@cnsd,field(i),'UniformOutput',false);
    end
end

%**************************************************************************

Contact us at files@mathworks.com