Home > php教程 > php手册 > National Weather Forecast Data Interface Calling PHP Example

National Weather Forecast Data Interface Calling PHP Example

WBOY
Release: 2016-10-22 00:00:33
Original
1351 people have browsed it

Code sample for PHP-based aggregated data national weather forecast API service request
This code sample is a code sample for PHP-based aggregate data national weather forecast API service request. Before using it, you need:
①: Apply for a weather forecast API appkey through https://www.juhe.cn/docs/api/id/39

The sample code includes the implementation of obtaining the list of supported cities, obtaining the weather forecast based on the city, requesting the weather forecast based on the IP address, requesting the weather based on the GPS coordinates, and the 3-hour weather forecast for the city. The sample code mainly parses some common fields. If you need complete or other fields not included, you can refer to the official interface and make modifications.

First: introduce the encapsulated weather calling class header('Content-type:text/html;charset=utf-8'); <br> include 'class.juhe.weather.php'; //Introduce weather request class <br> <br> //Interface basic information configuration <br> $appkey = '************'; //The weather query appkey you applied for <br> $weather = new weather($appkey); 1. Get the list of supported cities
Since the list of supported cities will basically not change like this, you can get the list and build it into your own application, so you don't have to request the API every time. $citysResult = $weather->getCitys(); <br> if($citysResult['error_code'] == 0){ //The following can be rewritten according to actual business needs <br> ///////////////////////////////////////////////////// ///////////////////// <br> $citys = $citysResult['result']; <br> foreach($citys as $ckey =>$c){ <br> echo "ID: ".$c['id'].", Province: ".$c['province'].", City: ".$c['city'].", Region: ".$c ['district']."<br>"; <br> } <br> }else{ //The following can be rewritten according to actual business needs <br> ///////////////////////////////////////////////////// ///////////////////// <br> echo $citysResult['error_code'].":".$citysResult['reason']; <br> } 2. Get weather forecast based on city/ID
Get the weather forecast through the name of the city or the ID of the city. The city ID is the field ID returned in the city support list $cityWeatherResult = $weather->getWeather('Suzhou'); <br> if($cityWeatherResult['error_code'] == 0){ //The following can be rewritten according to actual business needs <br> ///////////////////////////////////////////////////// ///////////////////// <br> $data = $cityWeatherResult['result']; <br> Echo "=======Current weather conditions=======<br>"; <br> echo "Temperature: ".$data['sk']['temp']." "; <br> echo "Wind direction: ".$data['sk']['wind_direction']." (".$data['sk']['wind_strength'].")"; <br> echo "Humidity:".$data['sk']['humidity']." "; <br> echo "<br><br>"; <br> <br> echo "=======Weather forecast for the next few days=======<br>"; <br> foreach($data['future'] as $wkey =>$f){ <br> echo "Date:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."< br>"; <br> } <br> echo "<br><br>"; <br> <br> echo "========Related weather index=======<br>"; <br> echo "Dressing index: ".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>"; <br>echo "UV intensity:".$data['today']['uv_index']."<br>"; <br> echo "Comfort index:".$data['today']['comfort_index']."<br>"; <br> echo "Car wash index:".$data['today']['wash_index']; <br> echo "<br><br>"; <br> <br> }else{ <br> Echo $cityWeatherRe3. Request the corresponding weather forecast based on the user’s IP address
The weather forecast for the user's location is obtained through the user's IP address. Since there may be errors in IP address resolution, sometimes the city located is not necessarily the user's actual location. $ipWeatherResult = $weather->getWeatherByIP('58.215.154.128'); <br> if($ipWeatherResult['error_code'] == 0){ //The following can be rewritten according to actual business needs <br> ///////////////////////////////////////////////////// ///////////////////// <br> $data = $ipWeatherResult['result']; <br> Echo "========Current city=======<br>"; <br> Echo $data['today']['city']; <br> echo "<br><br>"; <br> Echo "=======Current weather conditions=======<br>"; <br> echo "Temperature: ".$data['sk']['temp']." "; <br> echo "Wind direction: ".$data['sk']['wind_direction']." (".$data['sk']['wind_strength'].")"; <br> echo "Humidity:".$data['sk']['humidity']." "; <br> echo "<br><br>"; <br> <br> echo "=======Weather forecast for the next few days=======<br>"; <br> foreach($data['future'] as $wkey =>$f){ <br> echo "Date:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."< br>"; <br> } <br> echo "<br><br>"; <br> <br> echo "========Related weather index=======<br>"; <br> echo "Dressing index: ".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>"; <br> echo "UV intensity:".$data['today']['uv_index']."<br>"; <br> echo "Comfort index:".$data['today']['comfort_index']."<br>"; <br> echo "Car wash index:".$data['today']['wash_index']; <br> echo "<br><br>"; <br> <br> }else{ <br> echo $ipWeatherResult['error_code'].":".$ipWeatherResult['reason']; <br> } 4. Get the weather in the corresponding area based on GPS coordinates
Regardless of the weather forecast obtained through 2, 3, or 4, because the aggregation format is unified, the parsing process is consistent, so there are no additional operations, except for some differences in parameter transmission. $geoWeatherResult = $weather->getWeatherByGeo(116.401394,39.916042); <br> if($geoWeatherResult['error_code'] == 0){ //The following can be rewritten according to actual business needs <br> ///////////////////////////////////////////////////// ///////////////////// <br>$data = $geoWeatherResult['result']; <br> Echo "========Current city=======<br>"; <br> Echo $data['today']['city']; <br> echo "<br><br>"; <br> Echo "=======Current weather conditions=======<br>"; <br> echo "Temperature: ".$data['sk']['temp']." "; <br> echo "Wind direction: ".$data['sk']['wind_direction']." (".$data['sk']['wind_strength'].")"; <br> echo "Humidity:".$data['sk']['humidity']." "; <br> echo "<br><br>"; <br> <br> echo "=======Weather forecast for the next few days=======<br>"; <br> foreach($data['future'] as $wkey =>$f){ <br> echo "Date:".$f['date']." ".$f['week']." ".$f['weather']." ".$f['temperature']."< br>"; <br> } <br> echo "<br><br>"; <br> <br> echo "========Related weather index=======<br>"; <br> echo "Dressing index: ".$data['today']['dressing_index']." , ".$data['today']['dressing_advice']."<br>"; <br> echo "UV intensity:".$data['today']['uv_index']."<br>"; <br> echo "Comfort index:".$data['today']['comfort_index']."<br>"; <br> echo "Car wash index:".$data['today']['wash_index']; <br> echo "<br><br>"; <br> <br> }else{ <br> echo $geoWeatherResult['error_code'].":".$geoWeatherResult['reason']; <br> } 5. Get the three-hour city forecast
It is the city’s weather conditions every 3 hours $forecastResult = $weather->getForecast("Suzhou"); <br> if($forecastResult['error_code'] == 0){ //The following can be rewritten according to actual business needs <br> ///////////////////////////////////////////////////// ///////////////////// <br> $data = $forecastResult['result']; <br> foreach($data as $key => $d){ <br> echo "Date:".$d['date']." (".$d['sh']."point-".$d['eh']."point) ".$d['weather' ]." ".$d['temp1']."~".$d["temp2"]."<br>"; <br> } <br> }else{ //The following can be rewritten according to actual business needs <br> ///////////////////////////////////////////////////// ///////////////////// <br> echo $forecastResult['error_code'].":".$forecastResult['reason']; <br> } Through the above sample code, everyone should have a general understanding of how to call the aggregated data weather forecast API.
Finally, put the complete code of class.juhe.weather.php: <!--?php <br /> // +-------------------------------------------------- ----------------------- <br /> // | JuhePHP [ NO ZUO NO DIE ] <br /> // +-------------------------------------------------- ----------------------- <br />// | Copyright (c) 2010-2015 http://juhe.cn All rights reserved. <br /> // +-------------------------------------------------- ----------------------- <br /> // | Author: Juhedata <info@juhe.cn--> <br> // +-------------------------------------------------- ----------------------- <br> <br> //---------------------------------- <br> // Aggregated data weather forecast interface request class <br> //---------------------------------- <br> class weather{ <br> Private $appkey = false; //Application for aggregated weather forecast APPKEY <br> <br> Private $cityUrl = 'http://v.juhe.cn/weather/citys'; //City List API URL <br> <br> Private $weatherUrl = 'http://v.juhe.cn/weather/index'; //Request weather API URL based on city <br> <br> Private $weatherIPUrl = 'http://v.juhe.cn/weather/ip'; //Request weather API URL based on IP address <br> <br> Private $weatherGeoUrl = 'http://v.juhe.cn/weather/geo'; //Get weather API URL based on GPS coordinates <br> <br> Private $forecast3hUrl = 'http://v.juhe.cn/weather/forecast3h'; //Get the city weather 3-hour forecast API URL <br> <br> Public function __construct($appkey){ <br>          $this->appkey = $appkey; <br> } <br> <br> /**<br> * Get the weather forecast supported city list <br> * * @return array <br> ​​*/ <br> Public function getCitys(){ <br>           $params = 'key='.$this->appkey; <br> $ Content = $ This- & gt; juhecurl ($ this-& gt; cityurl, $ params); <br>            return $this->_returnArray($content); <br> } <br> <br> /**<br> * Get detailed weather forecast based on city name/ID <br> * @param string $city [city name/ID] <br> * * @return array <br> ​​*/ <br> Public function getWeather($city){ <br>         $paramsArray = array( <br> 'Key' = & gt; $ this- & gt; appKey, <br> ‘cityname’ => $city, <br>                                                                                                                                                                                                                                                                                                 ); <br> ​​​​$params = http_build_query($paramsArray); <br> $ Content = $ This- & gt; juhecurl ($ this-& gt; weatherurl, $ params); <br>            return $this->_returnArray($content); <br> } <br> <br> /**<br> * Get local weather forecast based on IP address <br> * @param string $ip [IP address] <br> * * @return array <br> ​​*/ <br> Public function getWeatherByIP($ip){ <br>            $paramsArray = array( <br> 'Key' = & gt; $ this- & gt; appKey, <br>            'ip'  => $ip,  <br>             'format'    => 2  <br>         );  <br>         $params = http_build_query($paramsArray);  <br>         $content = $this->juhecurl($this->weatherIPUrl,$params);  <br>         return $this->_returnArray($content);  <br>     }  <br>   <br>     /**<br> * Get local weather forecast based on GPS coordinates <br> * @param string $lon [longitude] <br> * @param string $lat [Latitude] <br> * * @return array <br> ​​*/  <br>     public function getWeatherByGeo($lon,$lat){  <br>         $paramsArray = array(  <br>             'key'   => $this->appkey,  <br>             'lon'  => $lon,  <br>             'lat'   => $lat,  <br>             'format'    => 2  <br>         );  <br>         $params = http_build_query($paramsArray);  <br>         $content = $this->juhecurl($this->weatherGeoUrl,$params);  <br>         return $this->_returnArray($content);  <br>     }  <br>   <br>     /**<br> * Get the three-hour city forecast <br> * @param string $city [city name] <br> * * @return array <br> ​​*/  <br>     public function getForecast($city){  <br>         $paramsArray = array(  <br>             'key'   => $this->appkey,  <br>             'cityname'  => $city,  <br>             'format'    => 2  <br>         );  <br>         $params = http_build_query($paramsArray);  <br>         $content = $this->juhecurl($this->forecast3hUrl,$params);  <br>         return $this->_returnArray($content);  <br>     }  <br>   <br>     /**<br> * Convert JSON content into data and return <br> * @param string $content [content] <br> * * @return array <br> ​​*/  <br>     public function _returnArray($content){  <br>         return json_decode($content,true);  <br>     }  <br>   <br>     /** <br>      * 请求接口返回内容 <br>      * @param  string $url [请求的URL地址] <br>      * @param  string $params [请求的参数] <br>     * @param  int $ipost [是否采用POST形式] <br>      * @return  string <br>      */  <br>     public function juhecurl($url,$params=false,$ispost=0){  <br>         $httpInfo = array();  <br>         $ch = curl_init();  <br>   <br>         curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );  <br>         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' );  <br>         curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );  <br>         curl_setopt( $ch, CURLOPT_TIMEOUT , 30);  <br>         curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );  <br>         if( $ispost )  <br>         {  <br>             curl_setopt( $ch , CURLOPT_POST , true );  <br>             curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );  <br>             curl_setopt( $ch , CURLOPT_URL , $url );  <br>         }  <br>         else  <br>         {  <br>             if($params){  <br>                 curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );  <br>             }else{  <br>                 curl_setopt( $ch , CURLOPT_URL , $url);  <br>             }  <br>         }  <br>         $response = curl_exec( $ch );  <br>         if ($response === FALSE) {  <br>             //echo "cURL Error: " . curl_error($ch);  <br>             return false;  <br>         }  <br>         $httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );  <br>         $httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );  <br>         curl_close( $ch );  <br>         return $response;  <br>     }  <br>   <br> }  

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template