Weather.class.php 2.21 KB
<?php
class Util_Weather
{
	/**
	 * 操作区天气
	 * 
	 * @param string $city
	 * @return string
	 */
	public static function operationWeather($city)
	{
		if(empty($city))
		{
			$city = 'beijing';
		}
    	$xml = simplexml_load_file('http://www.google.com/ig/api?weather='.$city.'&hl=zh-cn&oe=utf-8');
		$information = $xml->xpath("/xml_api_reply/weather/forecast_information");
		if (isset($information))
		{
			// 拼装当前的天气情况
			$current = $xml->xpath("/xml_api_reply/weather/current_conditions");
            $forecast_list = $xml->xpath("/xml_api_reply/weather/forecast_conditions");
            $weatherTpl = simplexml_load_file(dirname(__FILE__).'/resources/googleWeather.current.tpl.xml');
			$img = $weatherTpl->xpath('/div/span[@class="current"]/img');
			$img[0]['src'] = 'http://www.google.com' . $current[0]->icon['data'];
			$citySpan = $weatherTpl->xpath('/div/span[@class="current"]/span[@class="city"]');
			$tempSpan = $weatherTpl->xpath('/div/span[@class="current"]/span[@class="temp"]');
			$condSpan = $weatherTpl->xpath('/div/span[@class="current"]/span[@class="condition"]');
			$citySpan[0][0] = $information[0]->city['data'];
			$tempSpan[0][0] = $current[0]->temp_c['data'];
			$condSpan[0][0] = $current[0]->condition['data'];
			
			$result = trim($weatherTpl->asXML(), '<?xml version="1.0"?>');

			// 拼装天气预报
			$forecastTpl = simplexml_load_file(dirname(__FILE__).'/resources/googleWeather.forecast.tpl.xml');
			
			foreach ($forecast_list as $forecast)
			{
				$forecastImg = $forecastTpl->xpath('/div/span[@class="forecast"]/img');
				$forecastImg[0]['src'] = 'http://www.google.com'.$forecast->icon['data'];
				$tempSpan = $forecastTpl->xpath('/div/span[@class="forecast"]/span[@class="temp"]');
				$condSpan = $forecastTpl->xpath('/div/span[@class="forecast"]/span[@class="condition"]');
				$daySpan = $forecastTpl->xpath('/div/span[@class="forecast"]/span[@class="weekday"]');
				
				$daySpan[0][0] = $forecast->day_of_week['data'];
				$tempSpan[0][0] = $forecast->low['data'].'° C - '.$forecast->high['data'].'° C';
				$condSpan[0][0] = $forecast->condition['data'];
				
				$result .= trim($forecastTpl->asXML(), '<?xml version="1.0"?>');
			}
        }
        return $result;
	}
}