<?php
/**
* 采集天氣預報
* @example
* weather::$cache = root.'chache/'; //如果不改緩存目錄,可以不寫
* $array = weather::get();
* @author lrenwang
* @e-mail [email protected]
*
*/
class weather{
/**
* 域名
*
* @var string
*/
static public $domain='http://qq.ip138.com';
/**
* 城市的連接
* @example /省份/城市.htm
*
* @var string
*/
static public $url='/weather/hebei/qinhuangdao.htm';
/**
* 緩存目錄
*
* @var string
*/
static public $cache='cache/';
/**
* 更新頻率,小時為單位
*
* @var unknown_type
*/
static public $h=1;
/**
* 天氣預報對應的圖片路徑
*
* @var unknown_type
*/
static public $img = 'images/weather/';
/**
* 獲得今日,明日天氣預報
*
* @return array
*/
static function get()
{
$time=time();
//緩存文件位置
$cache_file = self::$cache.'weather.dat';
//判斷緩存文件是否存在,沒有則生成
if(!is_file($cache_file)){
if(!is_dir(self::$cache))
mkdir(self::$cache,0777,true);
self::get_($cache_file);
}
//判斷緩存是否過期,過期則重新生成
if($time-filemtime($cache_file)>=3600*3){
self::get_($cache_file);
}
$arr=unserialize(file_get_contents($cache_file));
return $arr;
}
/**
* 獲得緩存
*
* @param unknown_type $cache_file
*/
static public function get_($cache_file)
{
$con = file_get_contents(self::$domain.self::$url);
preg_match('~<table width="700" borderColorDark="#ffffff".*?>(.*?)</table>~s',$con,$table);
preg_match_all('~<tr.*?>(.*?)</tr>~s',$table[1],$trs);
$i=0;
$array = array();
foreach ($trs[1] as $tr)
{
++$i;
preg_match_all('~<t[dh].*?>(.*?)</t[dh]>~s',$tr,$tds);
$array[0][] = self::I($tds[1][1]);
$array[1][] = self::I($tds[1][2]);
}
$array[0][1] = self::get_img($array[0][1]);
$array[1][1] = self::get_img($array[1][1]);
file_put_contents($cache_file,serialize($array));
}
/**
* 數據輸出測試
*
* @param unknown_type $data
* @param unknown_type $s
*/
static public function P($data,$s=0)
{
echo "<pre>";
if (is_array($data))
var_export($data);
else
echo $data;
echo '</pre>';
if ($s==0)
exit();
}
/**
* 轉碼
*
* @param unknown_type $str
* @return unknown
*/
static public function I($str)
{
return iconv('GB2312','UTF-8',$str);
}
/**
* 獲得圖片的URL,此處可擴展,把圖片抓取到本地, 增加訪問速度
*
* @param string $str
* @return string
*/
static public function get_img($str)
{
preg_match('~src=["/']?(.*?)["/']? ~s',$str,$p);
return self::$img.pathinfo($p[1],PATHINFO_BASENAME);
}
}
//print_r();
$weather = weather::get();
echo "<img src={$weather[0][1]}>";
?>