pxWeather

A PHP class to retrieve, parse, and organize weather data for easy access.

by Jonathan Abbett

Summary

pxWeather gives you easy access to National Weather Service forecasts and current conditions for integration into your PHP application. To improve performance and decrease load on the data source, pxWeather can cache weather data locally.

Requirements

PHP 4.1.0 or later, installed with cURL support

Download

The latest release is available for download at SourceForge.

Installation

  1. Decompress your .zip or .tar.gz file.
  2. Copy pxweather.inc.php to your PHP-enabled website.
  3. If you use PHP5, copy xmlize-php5.inc.php to the same directory on your website. If you use PHP4, copy xmlize-php4.inc.php.
  4. If you intend to use caching, create a new directory for cache files to live. Make sure it has proper read/write permissions set.

(NOTE: by default, pxWeather will use the local subdirectory "cache" to read/write cache files. You may use pxWeather's setOption method to set a different directory.)

Testing your installation

Test your installation with the following bit of code. This code assumes it's running in the same directory as pxweather/xmlize and that caching uses the default settings.

< ?php

    require_once("pxweather.class.php");
    $w = new Weather();
    $w->load();
    echo $w->getCurrent("temp.string");

? >

When you run it, you should see the current temperature for Boston, MA in degrees Farenheit and Celsius.

Configuring pxWeather

All pxWeather configuration is done through the class constructor and the class's setOption() method. The examples below assume you've already loaded pxweather.class.php, as above.

To set a city other than Boston, MA, call the constructor with the $city variable set:

< ?php
        
    $w = new Weather($city = "Miami");
        
? >

Sometimes, two cities (i.e. Portland, ME and Portland, OR) have the same name. So, in any case where there might be ambiguity, consider using the ICAO location code for your city. The FAA maintains a list of codes for the USA at https://pilotweb.nas.faa.gov/qryhtml/icao/USA.html

< ?php
        
    // Portland, OR
    $w = new Weather($city = "KPDX");
            
    // Portland, ME
    $w = new Weather($city = "KPWM");
            
?>

To force pxWeather to ignore its cache, and retrieve data directly from the source, you can call the constructor with the $force variable set to true:

< ?php
        
    $w = new Weather($city = "Austin", $force = true);
            
? >

Other, less-common settings can be changed with the setOption() method. For example, to disable caching:

< ?php
        
    $w = new Weather();
    $w->setOption("PXWEATHER_CACHE", false);
            
? >

Four options may be set this way:

PXWEATHER_URL (URL)
The URL used to retrieve XML weather data.
PXWEATHER_CACHE (true/false)
Enable/disable caching; enabled by default.
PXWEATHER_CACHEFOR (number)
Number of minutes to keep cached data; 60 by default.
PXWEATHER_CACHEAT (path)
The directory where cache files should be stored; 'cache' by default.

Accessing Data

pxWeather extracts four kinds of data from the XML feed:

  1. Current conditions
  2. Almanac times
  3. Forecasts
  4. Daycasts

Current conditions can be retrieved with the getCurrent() method, which takes a field name as argument. The following are valid field names:

Field NameExample Value
cityBoston, MA
longnameBoston, MA
identKBOS
latitude42.37
longitude-71.03
timezone-5
daylight_saving1
night0
weather_codePC
observation_nameKBOS (Boston, MA)
time5 PM EDT 24 JUN 05
temp.string86 F (30 C)
temp.F86
temp.C30
dewpt.string53 F (11 C)
dewpt.F53
dewpt.C11
rel_hum.string32 %
rel_hum.percent32
wind.stringSW at 17 knt
wind_directSW
wind_speed.knt17
heat_index.F84
pressure.string1016.7 mb (30.03 in)
pressure.mb1016.7
pressure.in30.03
skiesmostly cloudy
text_weatherhaze

The example from above:

< ?php
        
    require_once("pxweather.class.php");
    $w = new Weather();
    $w->load();
    echo $w->getCurrent('temp.string');
        
? >

Almanac times (sunrise, sunset) can be retrieved with the methods getSunrise() and getSunset(). They take no arguments, and return time strings in 12-hour format (i.e. 5:08 AM).

Forecasts include a day name, a weather code, a low or high temperature, and a text description of the forecast. Forecasts for approximately the next six days and nights can be retrieved with the getForecasts() method, which takes no arguments. The method returns an array containing all forecasts. The example below cycles through each forecast, translates its weather code into a readable string with the weatherString() method, and prints high/low temperatures and text forecast.

< ?php

    require_once("pxweather.class.php");
    $w = new Weather();
    $w->load();
    
    foreach($w->getForecasts() as $forecast)
    {
        echo "FORECAST FOR " . $forecast['day']. ":\n";
        echo $w->weatherString($forecast['weather']) . "\n";
    	
        if (isset($forecast['low_temp']))
            echo "Low temperature: " . $forecast['low_temp'] . "\n";

        if (isset($forecast['high_temp']))
            echo "High temperature: " . $forecast['high_temp'] . "\n";
    	    
        echo "Description: " . $forecast['text'] . "\n\n";
    	
    }
    
? >

Daycasts are very similar to forecasts, but are not split into individual day and night reports and do not have text forecast descriptions. An example like above:

        
< ?php

    require_once("pxweather.class.php");
    $w = new Weather();
    $w->load();
    
    foreach($w->getDaycasts() as $daycast)
    {
        echo "DAYCAST FOR " . $daycast['day']. ":\n";
        echo $w->weatherString($daycast['weather']) . "\n";

        if (isset($daycast['low_temp']))
            echo "Low temperature: " . $daycast['low_temp'] . "\n";

        if (isset($daycast['high_temp']))
            echo "High temperature: " . $daycast['high_temp'] . "\n\n";
    }
    
? >

If you want to inspect the entire weather data structure, use the toString() method:

< ?php
        
    require_once("pxweather.class.php");
    $w = new Weather();
    $w->load();
    $w->toString();

? >

Feedback and requests

SourceForge hosts a variety of forums to express your constructive feedback:

All feedback and requests should be channeled through those outlets, and not sent by e-mail.

Credits

Many thanks go to Hans Anderson for his XMLize utility, which makes short work of XML parsing. XMLize, which is included in this distribution, can be found at http://www.hansanderson.com/php/xml/