欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

PHP调用全国天气预报数据接口查询天气示例

程序员文章站 2022-06-29 22:39:07
本文实例讲述了php调用全国天气预报数据接口查询天气。分享给大家供大家参考,具体如下: 基于php的聚合数据全国天气预报api服务请求的代码样例 本代码示例是基于php...

本文实例讲述了php调用全国天气预报数据接口查询天气。分享给大家供大家参考,具体如下:

基于php的聚合数据全国天气预报api服务请求的代码样例

本代码示例是基于php的聚合数据全国天气预报api服务请求的代码样例,使用前你需要:

①:通过 申请一个天气预报api的appkey

样例代码包含了获取支持城市列表、根据城市获取天气预报、根据ip地址请求天气预报、根据gps坐标请求天气、城市3小时天气预报的实现。示例代码主要是解析一些常用字段,如需要完整或其他未包含的字段,可以自行参考官方的接口,进行修改。

首先:引入封装好的天气调用类

header('content-type:text/html;charset=utf-8');
include 'class.juhe.weather.php'; //引入天气请求类
//接口基本信息配置
$appkey = '**********'; //您申请的天气查询appkey
$weather = new weather($appkey);

一、获取支持的城市列表

由于支持的城市列表基本不会这么变化,大家可以获取到列表后内置到自己的应用中,就不用每次都去请求api。

$citysresult = $weather->getcitys();
if($citysresult['error_code'] == 0){  //以下可根据实际业务需求,自行改写
  //////////////////////////////////////////////////////////////////////
  $citys = $citysresult['result'];
  foreach($citys as $ckey =>$c){
    echo "id:".$c['id'].",省份:".$c['province'].",城市:".$c['city'].",区域:".$c['district']."<br>";
  }
}else{  //以下可根据实际业务需求,自行改写
  //////////////////////////////////////////////////////////////////////
  echo $citysresult['error_code'].":".$citysresult['reason'];
}

二、根据城市/id获取天气预报

通过城市的名称或城市的id来获取天气预报,城市id就是获取城市支持列表中返回的字段id

$cityweatherresult = $weather->getweather('苏州');
if($cityweatherresult['error_code'] == 0){  //以下可根据实际业务需求,自行改写
  //////////////////////////////////////////////////////////////////////
  $data = $cityweatherresult['result'];
  echo "=======当前天气实况=======<br>";
  echo "温度:".$data['sk']['temp']."  ";
  echo "风向:".$data['sk']['wind_direction']."  (".$data['sk']['wind_strength'].")";
  echo "湿度:".$data['sk']['humidity']."  ";
  echo "<br><br>";
  echo "=======未来几天天气预报=======<br>";
  foreach($data['future'] as $wkey =>$f){
    echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>";
  }
  echo "<br><br>";
  echo "=======相关天气指数=======<br>";
  echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>";
  echo "紫外线强度:".$data['today']['uv_index']."<br>";
  echo "舒适指数:".$data['today']['comfort_index']."<br>";
  echo "洗车指数:".$data['today']['wash_index'];
  echo "<br><br>";
}else{
  echo $cityweatherre
}

三、根据用户的ip地址请求对应的天气预报

通过用户的ip地址获取用户所在地的天气预报,由于ip地址解析可能会有误差,所以有时定位到的城市不一定是用户实际的所在地。

$ipweatherresult = $weather->getweatherbyip('58.215.154.128');
if($ipweatherresult['error_code'] == 0){  //以下可根据实际业务需求,自行改写
  //////////////////////////////////////////////////////////////////////
  $data = $ipweatherresult['result'];
  echo "=======当前城市=======<br>";
  echo $data['today']['city'];
  echo "<br><br>";
  echo "=======当前天气实况=======<br>";
  echo "温度:".$data['sk']['temp']."  ";
  echo "风向:".$data['sk']['wind_direction']."  (".$data['sk']['wind_strength'].")";
  echo "湿度:".$data['sk']['humidity']."  ";
  echo "<br><br>";
  echo "=======未来几天天气预报=======<br>";
  foreach($data['future'] as $wkey =>$f){
    echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>";
  }
  echo "<br><br>";
  echo "=======相关天气指数=======<br>";
  echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>";
  echo "紫外线强度:".$data['today']['uv_index']."<br>";
  echo "舒适指数:".$data['today']['comfort_index']."<br>";
  echo "洗车指数:".$data['today']['wash_index'];
  echo "<br><br>";
}else{
  echo $ipweatherresult['error_code'].":".$ipweatherresult['reason'];
}

四、根据gps坐标来获取对应地区的天气

无论通过二、三、四获取的天气预报,因为聚合格式都是统一的,所以解析的流程是一致的,所以没有额外的操作,只是传参上有点的差异。

$geoweatherresult = $weather->getweatherbygeo(116.401394,39.916042);
if($geoweatherresult['error_code'] == 0){  //以下可根据实际业务需求,自行改写
  //////////////////////////////////////////////////////////////////////
  $data = $geoweatherresult['result'];
  echo "=======当前城市=======<br>";
  echo $data['today']['city'];
  echo "<br><br>";
  echo "=======当前天气实况=======<br>";
  echo "温度:".$data['sk']['temp']."  ";
  echo "风向:".$data['sk']['wind_direction']."  (".$data['sk']['wind_strength'].")";
  echo "湿度:".$data['sk']['humidity']."  ";
  echo "<br><br>";
  echo "=======未来几天天气预报=======<br>";
  foreach($data['future'] as $wkey =>$f){
    echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>";
  }
  echo "<br><br>";
  echo "=======相关天气指数=======<br>";
  echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>";
  echo "紫外线强度:".$data['today']['uv_index']."<br>";
  echo "舒适指数:".$data['today']['comfort_index']."<br>";
  echo "洗车指数:".$data['today']['wash_index'];
  echo "<br><br>";
}else{
  echo $geoweatherresult['error_code'].":".$geoweatherresult['reason'];
}

五、获取城市三小时预报

就是城市每3小时的天气情况

$forecastresult = $weather->getforecast("苏州");
if($forecastresult['error_code'] == 0){  //以下可根据实际业务需求,自行改写
  //////////////////////////////////////////////////////////////////////
  $data = $forecastresult['result'];
  foreach($data as $key => $d){
    echo "日期:".$d['date']." (".$d['sh']."点-".$d['eh']."点) ".$d['weather']." ".$d['temp1']."~".$d["temp2"]."<br>";
  }
}else{  //以下可根据实际业务需求,自行改写
  //////////////////////////////////////////////////////////////////////
  echo $forecastresult['error_code'].":".$forecastresult['reason'];
}

通过上面的示例代码,大家应该对如果调用聚合数据天气预报api有了一个大体的了解。

最后放上class.juhe.weather.php完整代码:

<?php
// +----------------------------------------------------------------------
// | juhephp [ no zuo no die ]
// +----------------------------------------------------------------------
// | copyright (c) 2010-2015 http://juhe.cn all rights reserved.
// +----------------------------------------------------------------------
// | author: juhedata <info@juhe.cn-->
// +----------------------------------------------------------------------
//----------------------------------
// 聚合数据天气预报接口请求类
//----------------------------------
class weather{
  private $appkey = false; //申请的聚合天气预报appkey
  private $cityurl = 'http://v.juhe.cn/weather/citys'; //城市列表api url
  private $weatherurl = 'http://v.juhe.cn/weather/index'; //根据城市请求天气api url
  private $weatheripurl = 'http://v.juhe.cn/weather/ip'; //根据ip地址请求天气api url
  private $weathergeourl = 'http://v.juhe.cn/weather/geo'; //根据gps坐标获取天气api url
  private $forecast3hurl = 'http://v.juhe.cn/weather/forecast3h'; //获取城市天气3小时预报api url
  public function __construct($appkey){
    $this->appkey = $appkey;
  }
  /**
   * 获取天气预报支持城市列表
   * @return array
   */
  public function getcitys(){
    $params = 'key='.$this->appkey;
    $content = $this->juhecurl($this->cityurl,$params);
    return $this->_returnarray($content);
  }
  /**
   * 根据城市名称/id获取详细天气预报
   * @param string $city [城市名称/id]
   * @return array
   */
  public function getweather($city){
    $paramsarray = array(
      'key'  => $this->appkey,
      'cityname' => $city,
      'format'  => 2
    );
    $params = http_build_query($paramsarray);
    $content = $this->juhecurl($this->weatherurl,$params);
    return $this->_returnarray($content);
  }
  /**
   * 根据ip地址获取当地天气预报
   * @param string $ip [ip地址]
   * @return array
   */
  public function getweatherbyip($ip){
     $paramsarray = array(
      'key'  => $this->appkey,
      'ip' => $ip,
      'format'  => 2
    );
    $params = http_build_query($paramsarray);
    $content = $this->juhecurl($this->weatheripurl,$params);
    return $this->_returnarray($content);
  }
  /**
   * 根据gps坐标获取当地的天气预报
   * @param string $lon [经度]
   * @param string $lat [纬度]
   * @return array
   */
  public function getweatherbygeo($lon,$lat){
    $paramsarray = array(
      'key'  => $this->appkey,
      'lon' => $lon,
      'lat'  => $lat,
      'format'  => 2
    );
    $params = http_build_query($paramsarray);
    $content = $this->juhecurl($this->weathergeourl,$params);
    return $this->_returnarray($content);
  }
  /**
   * 获取城市三小时预报
   * @param string $city [城市名称]
   * @return array
   */
  public function getforecast($city){
    $paramsarray = array(
      'key'  => $this->appkey,
      'cityname' => $city,
      'format'  => 2
    );
    $params = http_build_query($paramsarray);
    $content = $this->juhecurl($this->forecast3hurl,$params);
    return $this->_returnarray($content);
  }
  /**
   * 将json内容转为数据,并返回
   * @param string $content [内容]
   * @return array
   */
  public function _returnarray($content){
    return json_decode($content,true);
  }
  /**
   * 请求接口返回内容
   * @param string $url [请求的url地址]
   * @param string $params [请求的参数]
   * @param int $ipost [是否采用post形式]
   * @return string
   */
  public function juhecurl($url,$params=false,$ispost=0){
    $httpinfo = array();
    $ch = curl_init();
    curl_setopt( $ch, curlopt_http_version , curl_http_version_1_1 );
    curl_setopt( $ch, curlopt_useragent , 'mozilla/5.0 (windows nt 10.0; wow64) applewebkit/537.36 (khtml, like gecko) chrome/41.0.2272.118 safari/537.36' );
    curl_setopt( $ch, curlopt_connecttimeout , 30 );
    curl_setopt( $ch, curlopt_timeout , 30);
    curl_setopt( $ch, curlopt_returntransfer , true );
    if( $ispost )
    {
      curl_setopt( $ch , curlopt_post , true );
      curl_setopt( $ch , curlopt_postfields , $params );
      curl_setopt( $ch , curlopt_url , $url );
    }
    else
    {
      if($params){
        curl_setopt( $ch , curlopt_url , $url.'?'.$params );
      }else{
        curl_setopt( $ch , curlopt_url , $url);
      }
    }
    $response = curl_exec( $ch );
    if ($response === false) {
      //echo "curl error: " . curl_error($ch);
      return false;
    }
    $httpcode = curl_getinfo( $ch , curlinfo_http_code );
    $httpinfo = array_merge( $httpinfo , curl_getinfo( $ch ) );
    curl_close( $ch );
    return $response;
  }
}

更多关于php相关内容感兴趣的读者可查看本站专题:《php curl用法总结》、《php网络编程技巧总结》、《php数组(array)操作技巧大全》、《php字符串(string)用法总结》、《php数据结构与算法教程》及《php中json格式数据操作技巧汇总

希望本文所述对大家php程序设计有所帮助。