Code Igniter Model for Fetching Yahoo Weather Temp and Conditions.

October 27th 2009

Comes with basic SQL for building the database. This script is designed to update weather once every 5 minutes. No need for cron, this will just pull data if the current information in the database is older than 5 minutes. It will also archive previous weather information for long term usage.

Visit Gist on Github

<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
/*
CREATE TABLE IF NOT EXISTS `weather` (
  `id` int(11) NOT NULL auto_increment,
  `timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  `recorded_at` datetime NOT NULL,
  `temp` float NOT NULL,
  `conditions` varchar(150) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
*/
class Weather extends Model {

	var $zip_code = '87525';

	var $recorded_at;
	var $timestamp;
	var $temp;
	var $conditions;

	function __construct(){
		parent::Model();
		$this->getLatest();
	}
	
	function getLatest(){
		
		# load from db first..
		$this->loadFromDatabase();
		
		# this will fetch and store weather..
		if($this->timeToGetNewWeather() == true):
			$this->fetchAndStoreWeather();
		endif;
		
	}
	
	private function timeToGetNewWeather(){
		if(strtotime($this->timestamp." +5 minutes") < time()):
			return true;
		endif;
		return false;
	}
	
	private function loadFromDatabase(){
		$this->db->order_by('timestamp','desc');
		$stats = $this->db->get('weather',1)->row();
		$this->temp = $stats->temp;
		$this->conditions = $stats->conditions;
		$this->recorded_at = $stats->recorded_at;
		$this->timestamp = $stats->timestamp;
	}
	
	private function fetchAndStoreWeather(){

		$url = 'http://weather.yahooapis.com/forecastrss?p='.$this->zip_code;
		$xml = $this->stream_remote_file($url);
		$weatherData = $this->simplexml->xml_parse($xml);
		
		$fields = array();
		$fields['temp'] = $weatherData['channel']['item']['yweather:condition']['@attributes']['temp'];
		$fields['conditions'] = $weatherData['channel']['item']['yweather:condition']['@attributes']['text'];
		$fields['recorded_at'] = date('Y-m-d H:i:s',strtotime($weatherData['channel']['item']['yweather:condition']['@attributes']['date']));

		$this->db->insert('weather', $fields);
		
		$this->loadFromDatabase();
		
	}
	
	private function stream_remote_file($url){
		$handle = fopen($url, "rb");
		$contents = stream_get_contents($handle);
		fclose($handle);
		return $contents;
 	}

}
?>
365 downloads

ADD YOUR COMMENT

(optional)
(optional)
Use (Gravatar) for your avatars.