微信公众平台 天气查询功能 api调用

百度天气查询api

输入例如:烟台天气

实现时将烟台传给weather()方法,然后返回数据赋值给data。

实现代码:

<span style="font-size:18px;">if($str == '天气' && !empty($str_key)){   //天气查询
                $data = $this->weather($str_key);
                if(empty($data->retData)){
                    $contentStr = "抱歉,没有查到\"".$str_key."\"的天气信息!";
                } else {
                    $contentStr = "【".$data->retData->city."天气预报】\n".$data->retData->today->date."日".
                    "\n\n今天\n".$data->retData->today->type."  ".$data->retData->today->lowtemp."~".$data->retData->today->hightemp."\n".$data->retData->today->fengxiang."  ".$data->retData->today->fengli."\n当前气温 ".$data->retData->today->curTemp."\n\n温馨提示:".$data->retData->today->index[0]->details."
                    \n\n明天\n".$data->retData->forecast[0]->type."  ".$data->retData->forecast[0]->lowtemp."~".$data->retData->forecast[0]->hightemp."\n".$data->retData->forecast[0]->fengxiang."  ".$data->retData->forecast[0]->fengli." 
                    \n\n后天\n".$data->retData->forecast[1]->type."  ".$data->retData->forecast[1]->lowtemp."~".$data->retData->forecast[1]->hightemp."\n".$data->retData->forecast[1]->fengxiang."  ".$data->retData->forecast[1]->fengli."";
                }
            }</span>

weather()方法:

<span style="font-size:18px;"> private function weather($n){
       
        if(!empty($n)){
            $ch = curl_init();
            $url = 'http://apis.baidu.com/apistore/weatherservice/recentweathers?cityname='.urlencode($n);
            $header = array(
                'apikey: xxxxxxxxxxxx',//key需要去注册获得
            );
            // 添加apikey到header
            curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            // 执行HTTP请求
            curl_setopt($ch , CURLOPT_URL , $url);
            $json = curl_exec($ch);
            return json_decode($json);
        } else {
            return null;
        }
    }</span>
curl_exec()返回json数据,需要调用json_decode()解析json数据后作为返回值返回。



你可能感兴趣的:(微信公众平台 天气查询功能 api调用)