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

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

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

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

①:通过https://www.juhe.cn/docs/api/id/39 申请一个天气预报API的appkey

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

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

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

一、获取支持的城市列表

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

  1. $citysResult = $weather->getCitys();
  2. if($citysResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写
  3. //////////////////////////////////////////////////////////////////////
  4. $citys = $citysResult['result'];
  5. foreach($citys as $ckey =>$c){
  6. echo "ID:".$c['id'].",省份:".$c['province'].",城市:".$c['city'].",区域:".$c['district']."<br>";
  7. }
  8. }else{ //以下可根据实际业务需求,自行改写
  9. //////////////////////////////////////////////////////////////////////
  10. echo $citysResult['error_code'].":".$citysResult['reason'];
  11. }

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

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

  1. $cityWeatherResult = $weather->getWeather('苏州');
  2. if($cityWeatherResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写
  3. //////////////////////////////////////////////////////////////////////
  4. $data = $cityWeatherResult['result'];
  5. echo "=======当前天气实况=======<br>";
  6. echo "温度:".$data['sk']['temp']." ";
  7. echo "风向:".$data['sk']['wind_direction']." (".$data['sk']['wind_strength'].")";
  8. echo "湿度:".$data['sk']['humidity']." ";
  9. echo "<br><br>";
  10. echo "=======未来几天天气预报=======<br>";
  11. foreach($data['future'] as $wkey =>$f){
  12. echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>";
  13. }
  14. echo "<br><br>";
  15. echo "=======相关天气指数=======<br>";
  16. echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>";
  17. echo "紫外线强度:".$data['today']['uv_index']."<br>";
  18. echo "舒适指数:".$data['today']['comfort_index']."<br>";
  19. echo "洗车指数:".$data['today']['wash_index'];
  20. echo "<br><br>";
  21. }else{
  22. echo $cityWeatherRe
  23. }

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

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

  1. $ipWeatherResult = $weather->getWeatherByIP('58.215.154.128');
  2. if($ipWeatherResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写
  3. //////////////////////////////////////////////////////////////////////
  4. $data = $ipWeatherResult['result'];
  5. echo "=======当前城市=======<br>";
  6. echo $data['today']['city'];
  7. echo "<br><br>";
  8. echo "=======当前天气实况=======<br>";
  9. echo "温度:".$data['sk']['temp']." ";
  10. echo "风向:".$data['sk']['wind_direction']." (".$data['sk']['wind_strength'].")";
  11. echo "湿度:".$data['sk']['humidity']." ";
  12. echo "<br><br>";
  13. echo "=======未来几天天气预报=======<br>";
  14. foreach($data['future'] as $wkey =>$f){
  15. echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>";
  16. }
  17. echo "<br><br>";
  18. echo "=======相关天气指数=======<br>";
  19. echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>";
  20. echo "紫外线强度:".$data['today']['uv_index']."<br>";
  21. echo "舒适指数:".$data['today']['comfort_index']."<br>";
  22. echo "洗车指数:".$data['today']['wash_index'];
  23. echo "<br><br>";
  24. }else{
  25. echo $ipWeatherResult['error_code'].":".$ipWeatherResult['reason'];
  26. }

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

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

  1. $geoWeatherResult = $weather->getWeatherByGeo(116.401394,39.916042);
  2. if($geoWeatherResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写
  3. //////////////////////////////////////////////////////////////////////
  4. $data = $geoWeatherResult['result'];
  5. echo "=======当前城市=======<br>";
  6. echo $data['today']['city'];
  7. echo "<br><br>";
  8. echo "=======当前天气实况=======<br>";
  9. echo "温度:".$data['sk']['temp']." ";
  10. echo "风向:".$data['sk']['wind_direction']." (".$data['sk']['wind_strength'].")";
  11. echo "湿度:".$data['sk']['humidity']." ";
  12. echo "<br><br>";
  13. echo "=======未来几天天气预报=======<br>";
  14. foreach($data['future'] as $wkey =>$f){
  15. echo "日期:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."<br>";
  16. }
  17. echo "<br><br>";
  18. echo "=======相关天气指数=======<br>";
  19. echo "穿衣指数:".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>";
  20. echo "紫外线强度:".$data['today']['uv_index']."<br>";
  21. echo "舒适指数:".$data['today']['comfort_index']."<br>";
  22. echo "洗车指数:".$data['today']['wash_index'];
  23. echo "<br><br>";
  24. }else{
  25. echo $geoWeatherResult['error_code'].":".$geoWeatherResult['reason'];
  26. }

五、获取城市三小时预报

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

  1. $forecastResult = $weather->getForecast("苏州");
  2. if($forecastResult['error_code'] == 0){ //以下可根据实际业务需求,自行改写
  3. //////////////////////////////////////////////////////////////////////
  4. $data = $forecastResult['result'];
  5. foreach($data as $key => $d){
  6. echo "日期:".$d['date']." (".$d['sh']."点-".$d['eh']."点) ".$d['weather']." ".$d['temp1']."~".$d["temp2"]."<br>";
  7. }
  8. }else{ //以下可根据实际业务需求,自行改写
  9. //////////////////////////////////////////////////////////////////////
  10. echo $forecastResult['error_code'].":".$forecastResult['reason'];
  11. }

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

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

  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | JuhePHP [ NO ZUO NO DIE ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2010-2015 http://juhe.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: Juhedata <info@juhe.cn-->
  8. // +----------------------------------------------------------------------
  9. //----------------------------------
  10. // 聚合数据天气预报接口请求类
  11. //----------------------------------
  12. class weather{
  13. private $appkey = false; //申请的聚合天气预报APPKEY
  14. private $cityUrl = 'http://v.juhe.cn/weather/citys'; //城市列表API URL
  15. private $weatherUrl = 'http://v.juhe.cn/weather/index'; //根据城市请求天气API URL
  16. private $weatherIPUrl = 'http://v.juhe.cn/weather/ip'; //根据IP地址请求天气API URL
  17. private $weatherGeoUrl = 'http://v.juhe.cn/weather/geo'; //根据GPS坐标获取天气API URL
  18. private $forecast3hUrl = 'http://v.juhe.cn/weather/forecast3h'; //获取城市天气3小时预报API URL
  19. public function __construct($appkey){
  20. $this->appkey = $appkey;
  21. }
  22. /**
  23. * 获取天气预报支持城市列表
  24. * @return array
  25. */
  26. public function getCitys(){
  27. $params = 'key='.$this->appkey;
  28. $content = $this->juhecurl($this->cityUrl,$params);
  29. return $this->_returnArray($content);
  30. }
  31. /**
  32. * 根据城市名称/ID获取详细天气预报
  33. * @param string $city [城市名称/ID]
  34. * @return array
  35. */
  36. public function getWeather($city){
  37. $paramsArray = array(
  38. 'key' => $this->appkey,
  39. 'cityname' => $city,
  40. 'format' => 2
  41. );
  42. $params = http_build_query($paramsArray);
  43. $content = $this->juhecurl($this->weatherUrl,$params);
  44. return $this->_returnArray($content);
  45. }
  46. /**
  47. * 根据IP地址获取当地天气预报
  48. * @param string $ip [IP地址]
  49. * @return array
  50. */
  51. public function getWeatherByIP($ip){
  52. $paramsArray = array(
  53. 'key' => $this->appkey,
  54. 'ip' => $ip,
  55. 'format' => 2
  56. );
  57. $params = http_build_query($paramsArray);
  58. $content = $this->juhecurl($this->weatherIPUrl,$params);
  59. return $this->_returnArray($content);
  60. }
  61. /**
  62. * 根据GPS坐标获取当地的天气预报
  63. * @param string $lon [经度]
  64. * @param string $lat [纬度]
  65. * @return array
  66. */
  67. public function getWeatherByGeo($lon,$lat){
  68. $paramsArray = array(
  69. 'key' => $this->appkey,
  70. 'lon' => $lon,
  71. 'lat' => $lat,
  72. 'format' => 2
  73. );
  74. $params = http_build_query($paramsArray);
  75. $content = $this->juhecurl($this->weatherGeoUrl,$params);
  76. return $this->_returnArray($content);
  77. }
  78. /**
  79. * 获取城市三小时预报
  80. * @param string $city [城市名称]
  81. * @return array
  82. */
  83. public function getForecast($city){
  84. $paramsArray = array(
  85. 'key' => $this->appkey,
  86. 'cityname' => $city,
  87. 'format' => 2
  88. );
  89. $params = http_build_query($paramsArray);
  90. $content = $this->juhecurl($this->forecast3hUrl,$params);
  91. return $this->_returnArray($content);
  92. }
  93. /**
  94. * 将JSON内容转为数据,并返回
  95. * @param string $content [内容]
  96. * @return array
  97. */
  98. public function _returnArray($content){
  99. return json_decode($content,true);
  100. }
  101. /**
  102. * 请求接口返回内容
  103. * @param string $url [请求的URL地址]
  104. * @param string $params [请求的参数]
  105. * @param int $ipost [是否采用POST形式]
  106. * @return string
  107. */
  108. public function juhecurl($url,$params=false,$ispost=0){
  109. $httpInfo = array();
  110. $ch = curl_init();
  111. curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );
  112. 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' );
  113. curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );
  114. curl_setopt( $ch, CURLOPT_TIMEOUT , 30);
  115. curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );
  116. if( $ispost )
  117. {
  118. curl_setopt( $ch , CURLOPT_POST , true );
  119. curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );
  120. curl_setopt( $ch , CURLOPT_URL , $url );
  121. }
  122. else
  123. {
  124. if($params){
  125. curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );
  126. }else{
  127. curl_setopt( $ch , CURLOPT_URL , $url);
  128. }
  129. }
  130. $response = curl_exec( $ch );
  131. if ($response === FALSE) {
  132. //echo "cURL Error: " . curl_error($ch);
  133. return false;
  134. }
  135. $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );
  136. $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );
  137. curl_close( $ch );
  138. return $response;
  139. }
  140. }