PHP微信開發---城市天氣查詢

misaka去年夏天發表於2015-10-26

首先,你需要找到一個獲取天氣的API,此處,我用的是百度的apistore,申請和使用API的網址:http://apistore.baidu.com/apiworks/servicedetail/112.html


登入百度賬號,並用手機傳送請求獲取apikey。有了apikey,可以按照它的示例來請求城市天氣了。(可以按照城市中文名,拼音,城市編號等來查詢)




你可以現在本地做測試,請求完成之後,再放到自己的域名空間的指令碼里。

測試的指令碼例如:(注意apikey填寫自己申請的)

header('Content-type:text/html;charset=UTF-8');

$ch = curl_init();
$url = 'http://apis.baidu.com/apistore/weatherservice/cityname?cityname=上海';
$header = array(
    'apikey: ',//你的apikey
);
// 新增apikey到header
curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// 執行HTTP請求
curl_setopt($ch , CURLOPT_URL , $url);
$res = curl_exec($ch);

$res = json_decode($res, true);
echo "<pre>";
print_r($res);
echo "</pre>";

$contentStr = "";

foreach($res as $k=>$v){
    if($k == "retData"){
        $contentStr = "城市:" . $v['city'] . "\n";
        $contentStr .= "日期:" . $v['date'] . "\n";
        $contentStr .= "天氣:" . $v['weather'] ."\n";
        $contentStr .= "平均氣溫:" . $v['temp'] . "℃\n";
        $contentStr .= "最低氣溫:" . $v['l_tmp'] ."℃\n";
        $contentStr .= "最高氣溫:" . $v['h_tmp'] . "℃\n";
        $contentStr .= "風力:" . $v['WS'] . "\n";
        $contentStr .= "風向:" . $v['WD'] . "\n";
        $contentStr .= "日出時間:" . $v['sunrise'] . "\n";
        $contentStr .= "日落時間:" . $v['sunset'] . "\n";
        $contentStr .= "經度:" . $v['longitude'] . "\n";
        $contentStr .= "緯度:" . $v['latitude'];
    }
}

echo $contentStr;


如果你填寫了自己的apikey,那麼應該能獲取到所請求的天氣了:





如果能返回正常的資料了,那麼就可以放到你的域名空間裡了。(公眾平臺裡開發者中心填寫的url,該url有連線微信介面等功能)


如果你看不懂下面的程式碼或者第一次接觸微信開發,可以參考:http://blog.csdn.net/misakaqunianxiatian/article/details/49401759


下面的程式碼是responseMsg的一部分:


    public function responseMsg(){
       
<span style="white-space:pre">	</span>//get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信發來的XML資料

      	//extract post data
		if(!empty($postStr)){
                
            //解析post來的XML為一個物件$postObj
        	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
        
        	$fromUsername = $postObj->FromUserName; //請求訊息的使用者
        	$toUsername = $postObj->ToUserName; //"我"的公眾號id
        	$keyword = trim($postObj->Content); //使用者傳送的訊息內容
            $time = time(); //時間戳
            $msgtype = 'text'; //訊息型別:文字
            $textTpl = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<Content><![CDATA[%s]]></Content>
						</xml>";

            if($postObj->MsgType == 'event'){ //如果XML資訊裡訊息型別為event
                if($postObj->Event == 'subscribe'){ //如果是訂閱事件
                    $contentStr = "歡迎訂閱misaka去年夏天!\n更多精彩內容:http://blog.csdn.net/misakaqunianxiatian";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
                    echo $resultStr;
                    exit();
                }
            }

            $which = mb_substr($keyword, 0, 2, 'UTF-8');//獲取要返回什麼樣的資訊

            if($which== "翻譯"){ //如果要進行翻譯
                //呼叫有道翻譯API進行翻譯

            }elseif($which == "天氣"){
                $wea = $which;
                $city = str_replace($wea, "", $keyword);

                $ch = curl_init();
                $url = 'http://apis.baidu.com/apistore/weatherservice/cityname?cityname=' . $city;
                $header = array('apikey: '); //此處的apikey使用自己申請的apikey,填在冒號之後

                // 新增apikey到header
                curl_setopt($ch, CURLOPT_HTTPHEADER  , $header);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                // 執行HTTP請求
                curl_setopt($ch , CURLOPT_URL , $url);
                $res = curl_exec($ch);
                $res = json_decode($res, true);
                $contentStr = "";
                foreach($res as $k=>$v){

                    if($k == "retData"){
                        $contentStr = "城市:" . $v['city'] . "\n";
                        $contentStr .= "日期:" . $v['date'] . "\n";
                        $contentStr .= "天氣:" . $v['weather'] ."\n";
                        $contentStr .= "平均氣溫:" . $v['temp'] . "℃\n";
                        $contentStr .= "最低氣溫:" . $v['l_tmp'] ."℃\n";
                        $contentStr .= "最高氣溫:" . $v['h_tmp'] . "℃\n";
                        $contentStr .= "風力:" . $v['WS'] . "\n";
                        $contentStr .= "風向:" . $v['WD'] . "\n";
                        $contentStr .= "日出時間:" . $v['sunrise'] . "\n";
                        $contentStr .= "日落時間:" . $v['sunset'] . "\n";
                        $contentStr .= "經度:" . $v['longitude'] . "\n";
                        $contentStr .= "緯度:" . $v['latitude'];
                    }
                }
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
                echo $resultStr;
                exit();

            }else{
                $contentStr = "輸入翻譯XXX可以進行翻譯(=・ω・=)\n\n輸入天氣XX可以查詢城市天氣";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);
                echo $resultStr;
                exit();
            }


完成之後(別忘了填寫apikey),你的訂閱號裡,輸入天氣上海,那麼應該能查到上海當天的天氣了。

相關文章