Public platform development (5) weather forecast function development, public weather forecast
I. Introduction
The previous articles briefly introduced the activation and simple use of the public platform, but they did not involve problems in actual use, such as weather query, bus query, and express delivery query. The following articles describe some features that are frequently used in real life for your reference.
This article will develop weather queries that everyone cares about every day. For example, if a user sends the message "Suzhou weather", the user will return the real-time weather conditions in Suzhou, and the weather conditions in the next two or even five days.
Ii. Train of Thought Analysis
First of all to the user sent to the message to determine whether the message contains the "Weather" keyword, if it contains, You need to continue to extract regional information, and then through the China weather network (http://www.weather.com.cn) provides open APIs for weather query in relevant regions.
3. Keyword judgment and regional reading
The format of the message sent by the user to query the weather is fixed, that is, "region + weather". Therefore, first extract the last two words and determine whether the keyword is "Weather.
Use the php function mb_substr () to intercept the function. usage of this function:
Mb_substr-obtain the part of the string
string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] )
Note: perform a multi-byte safe substr () operation based on the number of characters. The position is counted from the start of str. The first character is 0. The second character is 1, and so on.
Parameters:
Str
Extract the substring from the string.
Start
The position of the first character to be used in str.
Positive number-> starting from the specified position at the beginning of the string;
Negative-> Start from the specified position at the end of the string;
Length
The maximum number of characters to use in str.
Positive number-> starting from start, it can contain a maximum of length characters;
Negative-> the length at the end of the string will be missed (if start is a negative number, it starts from the beginning of the string ).
Encoding
The encoding parameter is character encoding. If omitted, internal character encoding is used.
Return Value:
The mb_substr () function returns the specified part of str Based on the start and length parameters.
$str = mb_substr($keyword,-2,2,"UTF-8");
Start with the second character at the end of the message, intercept two characters, and then judge whether it is a keyword of "Weather.
Use the mb_substr () function to extract the region.
$ Str_key = mb_substr ($ keyword, 0,-2, "UTF-8 ");
From the beginning of the message, cut off the two characters (weather) at the end and get the region keyword.
Then, you can call the function to query the weather data.
If ($ str = 'Weather '&&! Empty ($ str_key) {// call the function to query weather data}
4. Call the weather () function to query
Here we call the weather forecast API interface provided by the China National Meteorological Administration, interface address: http://m.weather.com.cn/data/101190401.html
The number in the URL indicates the city number 101190401 (Suzhou). The corresponding relationship between other cities is provided below.
The interface returns comprehensive information, which is also provided in json format. The format is as follows:
{"Weatherinfo": {// basic information; "city": "suzhou", "city_en": "suzhou", "date_y": "August July 9, 2013", "date ": "", "week": "Tuesday", "fchh": "18", "cityid": "101190401", // Celsius temperature "temp1": "30 ℃ ~ 37 ℃ "," temp2 ":" 30 ℃ ~ 37 ℃ "," temp3 ":" 29 ℃ ~ 35 ℃ "," temp4 ":" 27 ℃ ~ 33 ℃ "," temp5 ":" 27 ℃ ~ 31 ℃ "," temp6 ":" 27 ℃ ~ 35 ℃ ", // Fahrenheit temperature;" tempF1 ":" 86 minutes ~ 98.6 bytes "," tempF2 ":" 86 bytes ~ 98.6 bytes "," tempF3 ":" 84.2 bytes ~ 95th percentile "," tempF4 ":" 80.6 ~ 91.4 bytes "," tempF5 ":" 80.6 bytes ~ 87.8 bytes "," tempF6 ":" 80.6 bytes ~ 95th percentile ", // weather description;" weather1 ":" clear to cloudy "," weatsp2 ":" clear to cloudy "," weather3 ":" clear to cloudy "," weather4 ": "Cloudy", "weather5": "thundershower to moderate rain", "weather6": "thundershower to multi-cloud", // weather description picture no. "img1": "0 ", "img2": "1", "img3": "0", "img4": "1", "img5": "0", "img6": "1 ", "img7": "1", "img8": "99", "img9": "4", "img10": "8", "img11": "4 ", "img12": "1", // image name; "img_single": "1", "img_title1": "clear", "img_title2": "Cloudy ", "img_title3": "clear", "img_title4": "Multi-cloud", "img_title5": "clear", "img_title6": "Multi-cloud", "img _ Title7 ":" Cloudy "," img_title8 ":" Cloudy "," img_title9 ":" thundershower "," img_title10 ":" moderate rain "," img_title11 ":" thundershower ", "img_title12": "Multi-cloud", "img_title_single": "Multi-cloud", // wind speed description "wind1": "Southwest 3-4", "wind2": "Southwest 3-4 ", "wind3": "southeast wind 3-4", "wind4": "southeast wind 3-4 to 4-5", "wind5": "southeast wind 4-5 to southwest wind 3-4 ", "wind6": "southwest wind 3-4 to 4-5", // wind speed description "fx1": "SouthWest Wind", "fx2": "SouthWest Wind", "fl1 ": "3-4", "fl2": "3-4", "fl3": "3-4", "fl4": "3-4 to 4-5", "fl5 ": "4-5 to 3-4", "fl6": "3-4 to 4-5", // Today's Dressing Index ;" Index ":" hot "," index_d ":" The weather is hot. It is recommended that you wear short shirts, short skirts, shorts, thin T-shirts, and other summer clothes. ", // Dressing Index for 48 hours" index48 ":" hot "," index48_d ":" The weather is hot. It is recommended that you wear clothes such as short shirts, short skirts, shorts, and thin T-shirts in summer. ", // UV and 48-hour UV" index_uv ":" medium "," index48_uv ":" medium ", // Car Wash Index" index_xc ":" suitable ", // tourism index "index_tr": "Not suitable", // comfort index "index_co": "Not Comfortable", "st1": "36", "st2 ": "28", "st3": "36", "st4": "28", "st5": "34", "st6": "27 ", // morning exercise Index "index_cl": "More suitable", // drying Index "index_ls": "More suitable", // allergy Index "index_ag": "less prone "}}
We can parse JSON to obtain the weather data of the corresponding city.
The weather () function is as follows:
private function weather($n){ include("weather_cityId.php"); $c_name=$weather_cityId[$n]; if(!empty($c_name)){ $json=file_get_contents("http://m.weather.com.cn/data/".$c_name.".html"); return json_decode($json); } else { return null; }}
Here we include a city correspondence file weather_cityId.php in the following format:
<? Php $ weather_cityId = array ("Beijing" => "101010100", "Shanghai" => "101020100", "Suzhou" => "101190401");?>
Obtain the city code based on the input city name. If it is not empty, call the China weather Network API to query the code, return json data, parse the data, and return the data, if it is null, the return value is null.
5. Organize the reply message form
Determines whether the returned data is null. If it is null, $ contentStr = "sorry, no weather information for \" ". $ str_key." \ "is found! ";
If the returned data is not empty:
$ ContentStr = "【". $ data-> weatherinfo-> city. "Weather Forecast] \ n ". $ data-> weatherinfo-> date_y. "". $ data-> weatherinfo-> fchh. "publish ". "\ n real-time weather \ n ". $ data-> weatherinfo-> weather1 ."". $ data-> weatherinfo-> temp1 ."". $ data-> weatherinfo-> wind1. "\ n tips :". $ data-> weatherinfo-> index_d. "\ n tomorrow \ n ". $ data-> weatherinfo-> weather2 ."". $ data-> weatherinfo-> temp2 ."". $ data-> weatherinfo-> wind2. "\ n day after tomorrow \ n ". $ data-> weatherinfo-> weather3 ."". $ data-> weatherinfo-> temp3 ."". $ data-> weatherinfo-> wind3;
Note:
$ Data-> weatherinfo-> city // obtain the city name, which is Suzhou
$ Data-> weatherinfo-> date_y // obtain the date, which is January 1, July 9, 2013.
$ Data-> weatherinfo-> fchh // data release time
$ Data-> weatherinfo-> weather1 // real-time weather
$ Data-> weatherinfo-> temp1 // Real-Time Temperature
$ Data-> weatherinfo-> wind1 // real-time wind direction and wind speed
$ Data-> weatherinfo-> index_d // Dressing Index
Weather, temp2, and wind2 represent tomorrow's weather, temperature, wind speed, and others.
\ N // indicates line feed
Vi. Test
VII. complete code
<? Php/*** wechat php test * // define your tokendefine ("TOKEN", "zhuojin"); $ wechatObj = new wechatCallbackapiTest (); $ 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 be due to the dif Ferent environments $ postStr = $ GLOBALS ["HTTP_RAW_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-> handleEvent ($ postObj ); break; default: $ resultStr = "Unknow msg type :". $ RX_TYPE; break;} echo $ resultStr;} else {echo ""; exit;} public function h AndleText ($ postObj) {$ fromUsername = $ postObj-> FromUserName; $ toUsername = $ postObj-> ToUserName; $ keyword = trim ($ postObj-> Content ); $ time = time (); $ textTpl = "<xml> <ToUserName> <! [CDATA [% s]> </ToUserName> <FromUserName> <! [CDATA [% s]> </FromUserName> <CreateTime> % s </CreateTime> <MsgType> <! [CDATA [% s]> </MsgType> <Content> <! [CDATA [% s]> </Content> <FuncFlag> 0 </FuncFlag> </xml> "; if (! Empty ($ keyword) {$ msgType = "text"; // weather $ str = mb_substr ($ keyword,-, "UTF-8 "); $ str_key = mb_substr ($ keyword, 0,-2, "UTF-8"); if ($ str = 'Weather '&&! Empty ($ str_key) {$ data = $ this-> weather ($ str_key); if (empty ($ data-> weatherinfo) {$ contentStr = "sorry, \ "" not found \"". $ str_key. "\" weather information! ";} Else {$ contentStr = "【". $ data-> weatherinfo-> city. "Weather Forecast] \ n ". $ data-> weatherinfo-> date_y. "". $ data-> weatherinfo-> fchh. "publish ". "\ n real-time weather \ n ". $ data-> weatherinfo-> weather1 ."". $ data-> weatherinfo-> temp1 ."". $ data-> weatherinfo-> wind1. "\ n tips :". $ data-> weatherinfo-> index_d. "\ n tomorrow \ n ". $ data-> weatherinfo-> weather2 ."". $ data-> weatherinfo-> temp2 ."". $ data-> weatherinfo-> wind2. "\ n day after tomorrow \ n ". $ data-> weatherinfo-> w Eather3 ."". $ data-> weatherinfo-> temp3 ."". $ data-> weatherinfo-> wind3;} else {$ contentStr = "thank you for choosing [zhuojin Suzhou ]". "\ n ". "No.: zhuojinsz ". "\ n ". "Excellent splendid, famous city Suzhou, we provide you with Suzhou local life guide, Suzhou related information query, the best Suzhou platform. ". "\ N ". "The current platform functions are as follows :". "\ n ". "[1] check the weather. For example, enter Suzhou weather ". "\ n ". "[2] Check the public transit. For example, enter: Suzhou Public Transit 178 ". "\ n ". "[3] Translation, such as input: translation I love you ". "\ n ". "[4] Suzhou information query, such as: Suzhou guanqian Street ". "\ n ". "For more information, please wait... ";}$ resultStr = sprintf ($ textTpl, $ fromUsername, $ toUsername, $ time, $ msgType, $ contentStr); echo $ resultStr ;} else {echo "Input something... ";}} public function handleEvent ($ object) {$ contentStr =" "; switch ($ object-> Event) {case" subscribe ": $ co NtentStr = "thank you for choosing zhuojin Suzhou ]". "\ n ". "No.: zhuojinsz ". "\ n ". "Excellent splendid, famous city Suzhou, we provide you with Suzhou local life guide, Suzhou related information query, the best Suzhou platform. ". "\ N ". "The current platform functions are as follows :". "\ n ". "[1] check the weather. For example, enter Suzhou weather ". "\ n ". "[2] Check the public transit. For example, enter: Suzhou Public Transit 178 ". "\ n ". "[3] Translation, such as input: translation I love you ". "\ n ". "[4] Suzhou information query, such as: Suzhou guanqian Street ". "\ n ". "For more information, please wait... "; break; default: $ contentStr =" Unknow Event :". $ object-> Event; break;} $ resultStr = $ this-> responseText ($ object, $ contentStr); return $ resultStr;} public function responseText ($ object, $ content, $ flag = 0) {$ textTpl = "<xml> <ToUserName> <! [CDATA [% s]> </ToUserName> <FromUserName> <! [CDATA [% s]> </FromUserName> <CreateTime> % s </CreateTime> <MsgType> <! [CDATA [text]> </MsgType> <Content> <! [CDATA [% s]> </Content> <FuncFlag> % d </FuncFlag> </xml> "; $ resultStr = sprintf ($ textTpl, $ object-> FromUserName, $ object-> ToUserName, time (), $ content, $ flag); return $ resultStr;} private function weather ($ n) {include ("weather_cityId.php"); $ c_name = $ weather_cityId [$ n]; if (! Empty ($ c_name) {$ json = file_get_contents ("http://m.weather.com.cn/data ". $ c_name. ". html "); return json_decode ($ json);} else {return null ;}} private 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 ;}}}?>
The city correspondence file weather_cityId.php has been updated to 2564 cities and will be added in the future. Please download it from the official online drive http://pan.baidu.com/s/1gfcbx6n.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.