首页 > 开发 > Php > 正文

php采集天气预报代码

2020-09-12 13:03:10
字体:
来源:转载
供稿:网友
<?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]}>";
?>



发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表