Weather forecast function of public platform development, public platform weather forecast
Recently there is a project demand for the public number on the addition of the weather forecast function, the use of Baidu provided by the car networking API V3.0 in the weather query function. First one final:
Project requirements: Have a good platform, Baidu registered account, need to open cloud platform in Baidu, add applications, get AK Code, PHP code editor, such as EditPlus
Below is a detailed introduction to the following development steps:
The first step: getting Ready for work
Log on to the public platform, check whether the server configuration is enabled, whether the URL (server address) has been configured token (token), and the token (the token) in the portal file that you wrote, such as: then click Submit, only to the Web page to prompt the green background of the submission success information, complete this step of the action
Step two: Weather forecast data source Preparation
With the registered Baidu account, login Baidu lbs cloud Platform, add an application, get access to the application AK, and understand the car-linked API V3.0, weather query function corresponding interface documentation to call the required weather information on demand.
The third step: public platform, interface file authoring jiekou.php
<?php/* worry-Free computer skills Network Public number function source code CopyRight All rights Reserved*/define ("TOKEN", "weixin2015"); $wechatObj = new WECHATCALLB Ackapitest (), if (!isset ($_get[' echostr ')) {$WECHATOBJ->responsemsg ();} else{$wechatObj->valid ();} Class wechatcallbackapitest{//Verify signature Public Function valid () {$echoStr = $_get["Echostr"]; $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) {echo $echoStr; Exit }} Public Function responsemsg () {//$postStr = $GLOBALS ["Http_raw_post_data"]; $postStr = file_get_contents ("Php://inpu T "); if (!empty ($POSTSTR)) {$this->logger ("R". $postStr); $POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', libxml_nocdata); $RX _type = Trim ($postObj->msgtype); $result = ""; Switch ($RX _type) {case "event": $result = $this->receiveevent ($POSTOBJ); Break CASE "text": $result = $this->receivetext ($POSTOBJ); Break } $this->logger ("T". $result); echo $result; }else {echo ""; Exit }} Private Function Receiveevent ($object) {switch ($object->event) {case "subscribe": $content = "Welcome attention to worry-free computer skills network"; Break } $result = $this->transmittext ($object, $content); return $result; The Private Function Receivetext ($object) {$keyword = Trim ($object->content);/////Get the information entered by the user//Determine weather if (!empty ($keyword)) { The!empty function determines whether the value obtained $keyword is empty $city = Mb_substr ($keyword, 0, 2, ' utf-8 '); Take the first two characters of the user input, such as "Huanggang Weather" final value "Huanggang" Include ("weather.php"); Call the weather interface file $content = Getweatherinfo ($city); Executes the Getweatherinfo method in the Weather interface file. Query Huanggang weather. } else{$content = Date ("Y-m-d h:i:s", Time ()). " \ n Technical support worry-free computer skills network \nwww.51pcjq.com "; Send the contents of the default reply for other content. } if (Is_array ($content)) {if (Isset ($content [0][' Picurl ')) {$result = $this->transmitnews ($object, $content);} else if (isset ($content [' Musicurl '])) {$result = $this->transmitmusic ($object, $content);}} else{$reSult = $this->transmittext ($object, $content); } return $result; } Private Function Transmittext ($object, $content) {if (!isset ($content) | | empty ($content)) {return "";} $TEXTTPL = "
%s
%s
%s
text
%s
"; $result = sprintf ($TEXTTPL, $object->fromusername, $object->tousername, Time (), $content); return $result; } Private Function Transmitnews ($object, $newsArray) {if (!is_array ($newsArray)) {return "";} $ITEMTPL = "
<! [cdata[%s]]>
%s
%s
%s
"; $item _str = ""; foreach ($newsArray as $item) {$item _str. = sprintf ($ITEMTPL, $item [' Title '], $item [' Description '], $item [' Picurl '], $it em[' URL ']); } $NEWSTPL = "
%s%s$item_str %s
news
%s
"; $result = sprintf ($NEWSTPL, $object->fromusername, $object->tousername, Time (), Count ($newsArray)); return $result; } Private Function Logger ($log _content) {}}
Fourth step: Use the Baidu car-linked API V3.0 interface, and access to the application AK code, number of weather interface source code:
weatger.php
<?phpfunction Getweatherinfo ($cityName) {if ($cityName = = "" | | (Strstr ($cityName, "+"))) {return "Send weather + city, e.g. ' Weather Shenzhen '";} User query weather, reply keyword rule $url = "http://api.map.baidu.com/telematics/v3/weather?location=". UrlEncode ($cityName). " &output=json&ak= self-applied Baidu Car link API ak Code ";//Build through the Baidu Car Union API V3.0 query Weather URL link $ch = Curl_init ();//Initialize session curl_setopt ($ch, Curlopt_url, $url);//Set Session Parameters curl_setopt ($ch, Curlopt_returntransfer, 1);//Set session Parameters $output = curl_exec ($ch);//Perform Curl session Curl_close ($ch);//Turn off the curl session $result = Json_decode ($output, true);//function Json_decode () to convert the JSON data format to an array. if ($result ["error"]! = 0) {return $result ["status"];} $curHour = (int) date (' H ', Time ()); $weather = $result ["Results"][0];//in accordance with the public number development document, the formation of multi-text reply message $weatherArray [] = Array ("Title" = = $weather [' currentcity '] ." Current weather: "." Temperature: ". $weather [' weather_data '][0][' temperature '].", ". $weather [' weather_data '][0][' weather '].", "." Winds: ". $weather [' Weather_data '][0][' Wind '].". "," Description "and" "," picurl "=" Http://weixin.51pcjq.com/img/weather_b "G.jpg "," Url "=" ""); for ($i = 0; $i < count ($weather ["Weather_data"]), $i + +) {$weatherArray [] = Array ("Title" = + $weather ["Weather_da Ta "[$i] [" date "]." \ n ". $weather ["Weather_data"] [$i] ["Weather"]. " ". $weather ["Weather_data"] [$i] [wind]. " ". $weather ["Weather_data"] [$i] ["Temperature"]. "," Description "and" "," Picurl "(($curHour >= 6) && ($ Curhour <)) $weather ["Weather_data"] [$i] ["Daypictureurl"]: $weather ["Weather_data"] [$i] [Nightpictureurl]], "Url" = "" "); } return $weatherArray;}? >
Precautions
Public platform tokens must be consistent with the token value in the interface file you write
To write PHP code, you need to use professional PHP editing tools, such as editplus,dreamweaver, etc.
The above weather interface file, Baidu Car Union API AK Code has been replaced by "self-applied Baidu car Union API AK Code: Please apply for, fill in your own
If you do not understand the place, you can pay attention to my Baidu space. Leave a message and contact me!
Weather forecast Development Latest code:
<?php header ("content-type:text/html;charset=utf-"); Date_default_timezone_set ("PRC"); /** * The first use is to provide the demo is always unsuccessful, using this online download success * * *//define your token define ("token", "DJJC"); $WECHATOBJ = new Wechatcallbackapitest (); Access operation, successfully access the direct comment on the line $wechatObj->responsemsg (); $WECHATOBJ->valid (); Class Wechatcallbackapitest {/*public function valid () {$echoStr = $_get["Echostr"]; Valid signature, option if ($this->checksignature ()) {echo $echoStr; exit;}} */Public Function responsemsg () {//get post data, May is due to the different environments $postStr = $GLOBALS ["Http_ra W_post_data "]; Extract post Data if (!empty ($POSTSTR)) {$POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', Libxml_ Nocdata); $RX _type = Trim ($postObj->msgtype); Switch ($RX _type) {case "text": $resultStr = $this->handletext ($POSTOBJ), break, Case "event": $resultStr = $this->h Andleevent ($POSTOBJ); Break Default: $resultStr = "Unknow msg type:". $RX _type; Break } Echo $resultStr;}else {echo ""; Exit }}//Test text reply public function Handletext ($POSTOBJ) {$fromUsername = $postObj->fromusername; $toUsername = $postObj Tousername; $keyword = Trim ($postObj->content); $time = time (); $TEXTTPL = "
%s
%s
%s
%s
%s
"; if (!empty ($keyword)) {$msgType = "text"; switch ($keyword) {case "Hello": $contentStr = "Hello!"; break, case "What's Your Name": $conte Ntstr = "I am a top robot"; break;//judge whether the weather case $keywords + "weather"; $str = Mb_substr ($keyword,-,, "utf-"); $str _key = mb_substr ($keyword,,-, "utf-"); if ($str = = "Weather") {$data = $this->weather ($str _key)->showapi_res_body; $data = ' [Today daytime] '. $data->f->day_ Weather. " \ n "; $data = ' [Today Night] '. $data->f->night_weather. " \ n "; $data = ' [Tomorrow Day] '. $data->f->day_weather. " \ n "; $data = ' [Tomorrow night] '. $data->f->night_weather. " \ n "; $CONTENTSTR = $data. $data. $data. $data; } break; Default: $CONTENTSTR = "Do not understand what you are talking about"; Break } $resultStr = sprintf ($TEXTTPL, $fromUsername, $toUsername, $time, $msgType, $CONTENTSTR); Echo $resultStr; }else{echo "Input something ...";} Public Function Handleevent ($object) {$contentStr = ""; Switch ($object->event) {case "subscribe": $CONTENTSTR = "Thank you for your attention to the top tutorial network, where you will get tons of free learning resources!" "; Break Default: $contentStr = "Unknow Event:". $object->event; Break }$RESULTSTR = $this->responsetext ($object, $CONTENTSTR); return $resultStr; The Public function responsetext ($object, $content) {$TEXTTPL = "
%s
%s
%s
text
%s
"; $RESULTSTR = sprintf ($TEXTTPL, $object->fromusername, $object->tousername, Time (), $content, $flag); return $resultStr; } Private Function Checksignature () {$signature = $_get["signature"]; $timestamp = $_get["timestamp"]; $nonce = $_get["n Once "]; $token = token; $TMPARR = Array ($token, $timestamp, $nonce); Sort ($TMPARR); $TMPSTR = implode ($TMPARR); $tmpStr = Sha ($TMPSTR); if ($tmpStr = = $signature) {return true;} else{return false;}} Weather forecast here Chinese characters need to deal with, think a lot of ways to not garbled private function weather ($k) {$n =urlencode ($k); $showapi _appid = ";//go to the relevant website to apply on the line $showapi _ Sign = ' Deafcacefdea '; $showapi _timestamp = Date (' Ymdhis '); $areaid = "; $PARAMARR = "; $needHourData = "; $url = Iconv (' GBK ', ' utf-', ' http://route.showapi.com/-? '. ') Area= '. $n. ' &areaid=&needhourdata=&needindex=&needmoreday=&showapi_appid= '. $showapi _appid. ' &showapi_timestamp= '. $showapi _timestamp. ' &showapi_sign= '. $showapi _sign); $result = file_get_contents ($url); $result = Json_decode ($result);return $result; }}?>
http://www.bkjia.com/PHPjc/1050140.html www.bkjia.com true http://www.bkjia.com/PHPjc/1050140.html techarticle The weather forecast function of public platform development, the public platform weather forecast recently has the project demand to the public number to add the weather forecast function, uses Baidu to provide the car networking API V3 ....