Location: PHPKode > scripts > phpWeather > phpweather/index.php
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);

/*
==============================================================================
                     phpWeather 1.2.2 by Kevin Cornwell
==============================================================================
 This script uses the free API from weatherBug.com servers availible on port
 80 (http).  I have made a very basic weather checker script that can return 
 any number of stations given a zip code.  I am using the "pipe delimeted"
 portion of the API because it's faster and requires less bandwidth than XML.  
 There are over 6,000 weather stations around the country on this network.  
 The number of stations vary from city to city with an average of about 15.  
 You can visit me at  www.kevincornwell.com and my email  is 
 hide@address.com  Enjoy! :)
 Demo site:
 http://www.kevincornwell.com/weather/index.php
==============================================================================



!!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!      


							  IMPORTANT!!!
YOU WILL NEED A API KEY FROM WEATHERBUG.COM IN ORDER FOR THIS SCRIPT TO WORK.
GO HERE TO GET THE KEY:  http://www.weatherbug.com/api/


!!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   !!!   



Once you have the key place it within the quotes.
Example:
$sMyKey = "A1234567890";
*/
$sMyKey = "A1234567890";
// Some servers allow you to use file_get_contents() set to true if you would 
// rather use that else we use the old fashioned method fsockopen().
// If you have problems with file_get_contents() set to false.
$bUseFGC = false;
/*
==============================================================================

To workaround the header issue error with php/IIS I opened the php.ini
(c:/windows/php.ini) file and enabled the following option...

; Output buffering allows you to send header lines (including cookies) even
; after you send body content, at the price of slowing PHP's output layer a
; bit.  You can enable output buffering during runtime by calling the output
; buffering functions.  You can also enable output buffering for all files by
; setting this directive to On.  If you wish to limit the size of the buffer
; to a certain size - you can use a maximum number of bytes instead of 'On', as
; a value for this directive (e.g., output_buffering=4096).
output_buffering = On

==============================================================================
                               Version History
==============================================================================

Verison 1.2.2 (5/26/2010)
Edited the connection timeout to make it a bit longer (their server must be slow).

Version 1.2.1 (9/8/2007)
Changed the form submit to GET rather than post so url links are user friendly.

Verion 1.2 (7/28/2006)
Added the option to use  fsockopen() or file_get_contents();

Version 1.1
Now using the offical "pipe delimited" weatherbug API.
Fixed server caching
Table sorting

Version 1.0.1
Fixed cookies.

Version 1.0
Initial Release.

==============================================================================
                                 MISC INFO
==============================================================================


(notice the file size differences)...
XML:
Station List (~2.19 kb): http://<licensecode>.api.wxbug.net/getStations.aspx?acode=<licensecode>&zipcode=<ZipCode>
Station Data (~3.23 kb): http://<licensecode>.api.wxbug.net/getLiveWeather.aspx?acode=<licensecode>&zipcode=<ZipCode>&StationID=<StationID>

PIPE DELIMITED:
Station list (~1.42 kb): http://<licensecode>.isapi.wxbug.net/wxdataisapi/wxdataisapi.dll?getstations&ZipCode=<ZipCode>&magic=21771
Station Data (~.217 kb): http://<licensecode>.isapi.wxbug.net/WxDataISAPI/WxDataISAPI.dll?Magic=10991&RegNum=0&Zi pCode=<ZIP>&StationID=<StationID>&Units=0&Version=7&Fore=0&t=<rnd#>

*/


// Lets do this...
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>phpWeather</title>
<script type="text/javascript" src="sorted_table.js"></script>
<script type="text/javascript">
<!--
	var sourceTable, destTable;
	onload = function() {
		sourceTable = new SortedTable('s');
		destTable = new SortedTable('d');
		mySorted = new SortedTable();
		mySorted.colorize = function() {
			for (var i=0;i<this.elements.length;i++) {
				if (this.elementIndex(this.elements[i]) % 2){
					this.elements[i].className = 'odd';
				} else {
					this.elements[i].className = 'even';
				}
			}
		}
		mySorted.onsort = mySorted.colorize;
		mySorted.colorize();
	}
	function moveRows(s,d) {
		var a = new Array();
		for (var o in s.selectedElements) {
			a.push(s.selectedElements[o]);
		}
		for (var o in a) {
			var elm = a[o];
			var tds = elm.getElementsByTagName('td');
			for (var i in tds) {
				if (tds[i].headers) tds[i].headers = d.table.id+''+tds[i].headers.substr(d.table.id.length);
			}
			d.body.appendChild(a[o]);
			d.deselect(a[o]);
			d.init(d.table);
			d.sort();
			s.deselect(a[o]);
			s.init(s.table);
		}
	}
//-->
</script>

<style>
/* common styles */
body {font-family:Georgia,sans-serif;font-size:62.5%;}
table {border:0;padding:0;margin:0 0 1em;border-left:1px solid #555;border-top:1px solid #555;font-size:1.2em;float:left;clear:left;}
tr {border:0;padding:0;margin:0;}
td, th {border:0;padding:1px;margin:0;border-right:1px solid #555;border-bottom:1px solid #555;background-color:#eee;}
td[axis='number'], td[axis='date'] {text-align:right;}
th {background-color:#ccc;padding:5px;}
tfoot td {border-top:1px solid #333;}
thead th {border-bottom:2px solid #333;}
dl {margin:0 1em;padding:0;}
dl, p, form {font-size:1.2em;float:left;}
hr {clear:both;width:100%;height:0;border:0;border-bottom:1px dashed #333;margin:0 0 1em;padding:0;}
/* sortedtable styles */
.hover td {background-color:#cce;}
.sortedminus {background-color:#ecc;}
.sortedplus {background-color:#cec;}
.selrow td {background-color:#aae;}
/* source-dest example styles */
#s {float:left;}
#d {float:left;clear:none;}
form#tabletool {margin:0;padding:0.5em;}
form#tabletool fieldset {width:8em;text-align:center;}
form#tabletool input {margin:0.5em;}
</style>
</head>
<body>
<h2>phpWeather</h2>

<?

//==============================================================================
//                                 Cookies
//==============================================================================

//  Retrive cookie if exists.
if (isset($_COOKIE["zipCode"])) {
    $zipCode = isset($HTTP_COOKIE_VARS["zipCode"]);
}
else {
    $zipCode = "32578"; //<<<<  SET DEFAULT ZIP HERE  <<<<
	// Set default zip cookie. 365 day expiration.
    setcookie("zipCode", $zipCode, time()+60*60*24*30*12);  
}

// If new zip is recieved then set.
if (array_key_exists('zip', $_GET)) {
    $zipCode = $_GET['zip'];
    setcookie("zipCode", $zipCode, time()+60*60*24*30);  // Set zip cookie.
}

//==============================================================================
//                               Input Box
//==============================================================================

echo '<form action="" method="get"><p align="center">Zip Code: ';
echo '<input style="width:60px;" type="text" name="zip" value="'.$zipCode.'" />&nbsp;';
echo '<input style="width:60px;" type="submit" value="Submit" /></p></form>';

//==============================================================================
//                               Main Logic
//==============================================================================

// Get station list and station info.
$arrStationInfo = getStationList();

$x = 0;

for ($i = 3; $i < count($arrStationInfo) - 1; $i=$i+6)  { // start at posistion index 3 (stationID, then skip every six to the next stationID)

    $arrStationData[$x] = getData($arrStationInfo[$i]); //nexted array with all data, all stations.
	$x++;
}

displayDataTable($arrStationData);

//==============================================================================
//                              Functions
//==============================================================================

// This function gets the station list data
// and returns it as an array.

function getStationList() {

	global $bUseFGC, $zipCode, $sMyKey;

    $sURL = "http://".$sMyKey.".isapi.wxbug.net/wxdataisapi/wxdataisapi.dll?getstations&ZipCode=".$zipCode."&magic=21771";
	
	$sFile = ($bUseFGC) ? file_get_contents($sURL, false) : get_file($sURL) ;
    
    return explode("|", $sFile);
/*
This is the data returned in the array...

Magic Number (21771)
NoofStations
ZipCode
StationID_1
Station Name
City, State
Distance from Zip Code center
Station_Type 0: Internet 1:Modem
City, State of Given ZipCode
StationID_2
Station Name
City, State
Distance from Zip Code center
Station_Type 0: Internet 1:Modem
City, State of Given ZipCode
StationID_3
Etc...
*/
}

//==============================================================================

// This functions returns a stations currnet
// weather data and returns it as a array.

function getData($stationID){
	
	global $bUseFGC, $zipCode, $sMyKey;
	
	$iRnd = rand(1,30000); //send random number with url to prevent server caching.
	
    $sURL = "http://".$sMyKey.".isapi.wxbug.net/WxDataISAPI/WxDataISAPI.dll?Magic=10991&RegNum=".$sMyKey."&ZipCode=".$zipCode."&StationID=".$stationID."&Units=0&Version=7&Fore=0&t=".$iRnd;

	$sFile = ( $bUseFGC ) ? file_get_contents($sURL, false) : get_file($sURL) ;

    return explode("|", $sFile);
/*
This is the data returned in the array...

Magic Number
Time
Date
Temperature
Wind direction	
Wind Speed
Gust Wind Direction
Gust Wind Speed
Today Rainfall
Rainfall Rate
Barometer
Humidity
High Temp
Low Temp
Dew Point
Wind Chill
Monthly Rain
Temperature Rate
Humidity Rate
Barometer Rate
High Humidity
Low Humidity
High Barometer
Low Barometer
Max Rain Rate
Gust Time
Average Wind Direction
Average Wind Speed
Indoor Temp
Auxiliary Temp
Light
Yearly Rainfall
Indoor Temp Rate
Aux Temp Rate
Light Rate
Station Name
City and State Name
Active Query Frequency (seconds)
Inactive/Background Query Frequency
*/
}

//==============================================================================

// This function displays the data in a table.
// *note: Several feilds are not used in the
// array and are thus left out of the table.

function displayDataTable($dataArray) {

	$arrColumns = explode("|", "Magic Number|Time|Date|Temp|Wind Direction|Wind Speed|Gust Wind Direction|Gust Wind Speed|Today Rainfall|Rainfall Rate|Barometer|Humidity|High Temp|Low Temp|Dew Point|Wind Chill|Monthly Rain|Temperature Rate|Humidity Rate|Barometer Rate|High Humidity|Low Humidity|High Barometer|Low Barometer|Max Rain Rate|Gust Time|Average Wind Direction|Average Wind Speed|Indoor Temp|Auxiliary Temp|Light|Yearly Rainfall|Indoor Temp Rate|Aux Temp Rate|Light Rate|Station Name|City and State Name");
	//$arrColumns = explode("|", "Magic Number|Time|Date|Temp|Wind Direction|Wind Speed|Gust Wind Direction|Gust Wind Speed|Today Rainfall|Rainfall Rate|Barometer|Humidity|High Temp|Low Temp|Dew Point|Wind Chill|Gust Time|Average Wind Direction|Average Wind Speed|City and State Name");
	
    // First build the column headers.
	echo "\r\n";
    echo "<table class='sorted' cellspacing='0' cellpadding='0'>\r\n<thead>\r\n<tr>\r\n";
	echo '<th id="id" class="sortedplus"><span>'.$arrColumns[35]."</span></th>\r\n";		//Make location first column.
	for ($i = 3; $i < count($arrColumns); $i++)  {
		echo '<th id="'.prepFormat($arrColumns[$i]).'"><span>'.$arrColumns[$i]."</span></th>\r\n";
	}
	
	echo "</tr>\r\n</thead>\r\n<tbody>\r\n";
		
	// Now build data table and fill it.
	for ($i = 0; $i < count($dataArray); $i++)  {
		echo "<tr>\r\n";
		echo '<td axis="string" headers="id">'.$dataArray[$i][35]."</td>\r\n";  //Make location first column (data).
		for ($x = 3; $x < count($arrColumns); $x++)  {
			echo '<td axis="string" headers="'.prepFormat($arrColumns[$x]).'">'.$dataArray[$i][$x]."</td>\r\n";
		}
		echo "</tr>\r\n";
	}
    echo "</tbody>\r\n";
	echo "</table>\r\n";
}


//==============================================================================


// Trim, strip excess whitespace, and make lowercase.
function prepFormat($content) {
	$content = preg_replace("/ +/", " ", trim($content));
	//trim spaces
	$content = str_replace(" ", "", $content);
	//to lower case
	$content = strtolower($content);
	return $content;
}


//==============================================================================


// when file_get_contents won't work on your server this is used.

function get_file($query){

		$url = parse_url($query);
		$host = $url["host"];
		$path = $url["path"] . "?" . $url["query"];

		flush();
		$timeout = 10;
		$fp = fsockopen ($host, 80, $errno, $errstr, $timeout)
		or die('Error can not open connection to wb API.');
		$buf = "";
		
		if ($fp) {
			fputs ($fp, "GET $path HTTP/1.0\nHost: " . $host . "\n\n");
			while (!feof($fp)) {
				$buf .= fgets($fp, 128);
			}
			$lines = split("\n", $buf);
			$data = $lines[count($lines)-1];
			fclose($fp);
		}
		return $data;
}
?>


<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
var pageTracker = _gat._getTracker("UA-71111-2");
pageTracker._initData();
pageTracker._trackPageview();
</script>



</body>
</html>

Return current item: phpWeather