PHP public platform development-weather forecast function development. [PHP public platform development series] 01. configure interface 02. public platform sample code analysis 03. subscribe processing 04. simple reply function development 05. API weather forecast function [PHP public platform development series] 01. configuration interface
02. public platform sample code analysis
03. subscribe processing
04. simple reply function development
05. API weather forecast function development
Address: http://www.phpchina.com/archives/view-43387-1.html
This series is provided by PHPChina's special Author @ David _tang. For more information, see the author information and the address of this article. I. INTRODUCTION
The previous articles briefly introduced the activation and simple use of the PHP 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-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 extracts the substring from the string. Position of the first character to be used in startstr. Positive number-> start from the specified position at the beginning of the string; negative number-> start from the specified position at the end of the string; maximum number of characters to be used in lengthstr. Positive-> start from start can contain a maximum of length characters; negative-> length characters at the end of string will be missed (if start is a negative number, start from the beginning of the string ). The encodingencoding 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,-, "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:
"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
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 different 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 handleText ($ postObj) {$ fromUsername = $ postObj-> FromUserName; $ toUsername = $ postObj-> ToUserName; $ keyword = trim ($ postObj-> Content); $ time = time (); $ textTpl ="
%s
%s
% S
%s
%s
0
"; 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 ="
%s
%s
% S
text
%s
% D
"; $ 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 is updated to 2564 cities and will be added later. please goLeshiDownload the official forum (URL: http://www.joythink.net.
========================================================== ========================
PHPChina platform activated!
Search for"
PHPChinaClick the Follow button to obtain the latest and most professional industry information pushed to you by PPC. more topics will be provided for you.
[PPC mining]: Provides you with stories about classic products and product people from time to time.
[PPC foreign language]: Share a foreign translation article from time to time
[Ppc q &]: Reply to users' questions on a daily basis.
[Coder Radio Pro]: Irregular broadcast programs
01. configuration interface 02. public platform sample code analysis 03. subscribe processing 04. simple reply function development 05. API weather forecast...