您好,登錄后才能下訂單哦!
這篇文章主要講解了“php怎么實現天氣預報功能”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“php怎么實現天氣預報功能”吧!
1.登錄百度ak申請:http://lbsyun.baidu.com/apiconsole/key
2.實現天氣信息功能
baiduWeather.php
<?php /** * 使用百度天氣預報接口獲取城市天氣信息案例實現 */ //獲取城市天氣信息 function getWeatherInfo($cityName){ if($cityName == "" || (strstr($cityName,"+"))){ return "發送城市加天氣,例如北京天氣"; } //獲取到的ak $ak = your ak; //獲取到的sk $sk = your sk; //調用接口 $url = 'http://api.map.baidu.com/telematics/v3/weather?ak=%s&location=%s&output=%s&sk=%s'; $uri = '/telematics/v3/weather'; $location = $cityName; $output = 'json'; $querystring_arrays = array( 'ak' => $ak, 'location' => $location, 'output' => $output ); $querystring = http_build_query($querystring_arrays); //生成sn $sn = md5(urlencode($uri.'?'.$querystring.$sk)); $targetUrl = sprintf($url,$ak,urlencode($location),$output,$sn); $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$targetUrl); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); $result = curl_exec($ch); curl_close($ch); $result = json_decode($result,true); if($result["error"]!=0){ return $result["status"]; } $curHour = (int)date('H',time()); $weather = $result["results"][0]; $weatherArray[]=array("Title"=>$weather['currentCity']."天氣預報","Description"=>"","PicUrl"=>"","Url"=>""); for($i = 0;$i<count($weather["weather_data"]);$i++){ $weatherArray[] = array("Title"=> $weather["weather_data"][$i]["data"]."\n". $weather["weather_data"][$i]["weather"]. $weather["weather_data"][$i]["wind"]. $weather["weather_data"][$i]["temperature"], "Description"=>"", "PicUrl"=>(($curHour>=6)&&($curHour< 18))?$weather["weather_data"][$i]["dayPictureUrl"]:$weather["weather_data"][$i]["nightPictureUrl"],"URL"=>"" ); } return $weatherArray; }
3.實現天氣消息事件
<?php /* CopyRight 2016 All Rights Reserved */ define("TOKEN", "weixin"); /** * 百度天氣預報案例實現 * 實現思路: * 1.申請百度ak、sk * 2.使用百度天氣預報接口 * 3.實現天氣信息功能 * 4.實現事件響應功能 */ $wechatObj = new wechatCallbackapiTest(); if (!isset($_GET['echostr'])) { $wechatObj->responseMsg(); }else{ $wechatObj->valid(); } class wechatCallbackapiTest { //驗證簽名 public function valid() { $echoStr = $_GET["echostr"]; if($this->checkSignature()){ header('content-type:text'); echo $echoStr; exit; } } public function checkSignature(){ $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr); $tmpStr = implode($tmpArr); $tmpStr = sha1($tmpStr); if($tmpStr == $signature) { return true; }else{ return false; } } //響應消息 public function responseMsg() { $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; if (!empty($postStr)){ $this->logger("R ".$postStr); $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $RX_TYPE = trim($postObj->MsgType); //消息類型分離 switch ($RX_TYPE) { case "event": $result = $this->receiveEvent($postObj); break; case "text": $result = $this->receiveText($postObj); break; default: $result = "unknown msg type: ".$RX_TYPE; break; } echo $result; }else { echo ""; exit; } } //接收事件消息 public function receiveEvent($object) { $content = ""; switch ($object->Event) { case "subscribe": $content = "歡迎關注Nicky的公眾號 "; $content .= (!empty($object->EventKey))?("\n來自二維碼場景 ".str_replace("qrscene_","",$object->EventKey)):""; break; case "unsubscribe": $content = "取消關注"; break; } $result = $this->transmitText($object, $content); return $result; } //接收文本消息 public function receiveText($object) { $keyword = trim($object->Content); //自動回復模式 if (strstr($keyword, "天氣")){ $city = str_replace('天氣','',$keyword); include("baiduweather.php"); $content = getWeatherInfo($city); } $result = $this->transmitNews($object, $content); return $result; } //回復圖文消息 public function transmitNews($object, $newsArray) { if(!is_array($newsArray)){ return; } $itemTpl = " <item> <Title><![CDATA[%s]]></Title> <Description><![CDATA[%s]]></Description> <PicUrl><![CDATA[%s]]></PicUrl> <Url><![CDATA[%s]]></Url> </item> "; $item_str = ""; foreach ($newsArray as $item){ $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']); } $xmlTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[news]]></MsgType> <ArticleCount>%s</ArticleCount> <Articles> $item_str</Articles> </xml>"; $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray)); return $result; } //日志記錄 public function logger($log_content) { if(isset($_SERVER['HTTP_APPNAME'])){ //SAE sae_set_display_errors(false); sae_debug($log_content); sae_set_display_errors(true); }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL $max_size = 10000; $log_filename = "log.xml"; if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);} file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND); } } } ?>
感謝各位的閱讀,以上就是“php怎么實現天氣預報功能”的內容了,經過本文的學習后,相信大家對php怎么實現天氣預報功能這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。