First, Introduction
Several previous articles on the micro-letter public platform for the opening and simple use did a simple introduction, but did not relate to the actual use of the problem, such as weather inquiries, bus inquiries, express inquiries. The next few articles will be used in real life will often use some of the functions of the development to explain, for the reader's reference.
This article will be on the daily concern of the weather query development, for example, the user sent a message "Suzhou Weather", will return to Suzhou real-time weather conditions, and the next two days or even the next five days weather conditions.
Second, the analysis of ideas
First, the user sent over the message to determine whether the message contains a "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) provided by the Open API for the relevant regional weather inquiries.
Third, the key word judgment and area reads
The user sent over to check the weather message format is fixed, that is, "area + weather", so first intercept the two words, judge whether the "weather" keyword.
Using the PHP function Mb_substr () intercept, about the use of this function:
Mb_substr-gets the part of the string
String Mb_substr (string $str, int $start [, int $length [, String $encoding]])
Description: Performs a multibyte-safe substr () operation based on the number of characters. The position is counted from the beginning of the Str. The position of the first character is 0. The position of the second character is 1, and so on.
Parameters:
Str
Extracts substrings from this string.
Start
The position of the first character to use in Str.
Positive-> start at the specified position at the beginning of the string;
The negative-> starts at the specified position at the end of the string;
Length
The maximum number of characters to use in Str.
A positive-> includes a maximum of length characters starting at start point;
The length character at the end of a negative-> string is omitted (if start is a negative number from the beginning of the string).
Encoding
The encoding parameter is a character encoding. If omitted, the internal character encoding is used.
return value:
The MB_SUBSTR () function returns the specified portion of STR based on the start and length parameters.
$str = Mb_substr ($keyword, -2,2, "UTF-8");
Intercepts the second character from the end of the message, intercepts two characters, and then determines whether it is a "weather" keyword.
Area extraction below, or using the Mb_substr () function.
$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 key.
Then make a judgment, and then call the function to query the weather data.
if ($str = = ' Weather ' &&!empty ($str _key))
{
//Call Function query weather data
}
Iv. call weather () function query
We are here to call the China National Meteorological Service Weather APIs API interface, interface address: http://m.weather.com.cn/data/101190401.html
The number in the URL refers to the city's number 101190401 (Suzhou), and other city correspondence will be provided below.
This interface returns the information in a more comprehensive and JSON format, in the following format:
{"Weatherinfo": {//basic information; "City": "Suzhou", "city_en": "Suzhou", "date_y": "July 9, 2013", "Date": "", "Week": "Tuesday", "Fchh": "A", "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℉~98.6℉ "," tempF2 ":" 86℉~98.6℉ "," tempF3 ":" 84.2℉~95℉ "," tempF4 ":" 80.6℉~91.4℉ "," tempF5 ":" 80.6℉~87.8℉ ","
TempF6 ":" 80.6℉~95℉ ",//Weather description;
"Weather1": "Clear to Cloudy", "Weather2": "Clear to Cloudy", "Weather3": "Sunny to Cloudy", "weather4": "Cloudy", "Weather5": "Thunderstorm to moderate Rain", "Weather6": "Thunderstorm to Cloudy",
Weather description Picture number "IMG1": "0", "Img2": "1", "IMG3": "0", "IMG4": "1", "Img5": "0", "Img6": "1", "Img7": "1", "Img8": "", "Img9": "4",
"Img10": "8", "Img11": "4", "Img12": "1",//Picture name; "Img_single": "1", "Img_title1": "Clear", "Img_title2": "Cloudy", "Img_title3": "Clear", "img_title4": "Cloudy", "img_title5": "Clear", "img_ Title6 ":" Cloudy "," Img_title7 ":" Cloudy "," Img_title8 ":" Cloudy "," img_title9 ":" Thunderstorm "," Img_title10 ":" Moderate Rain "," Img_title11 ":" Thunderstorm "," Img_title12 ":" Cloudy "," Img_title_single ":" Cloudy ",//wind speed description" Wind1 ":" Southwest 3-4 "," Wind2 ":"3-4 levels of south-west wind "," Wind3 ":" Southeast 3-4 Level "," Wind4 ":" The Southeast wind 3-4 to 4-5 class "," Wind5 ":" Southeast wind 4-5 degrees to the southwest of 3-4 level "," Wind6 ":" Southwest of 3-4 to 4-5 level ",//Speed level description Fx1 ":" Southwest Wind "," FX2 ":" South-West Wind "," FL1 ":" Level 3-4 "," FL2 ":" 3-4 "," Fl3 ":" 3-4 "," Fl4 ":" 3-4 to 4-5 level "," FL5 ":" 4-5 level to 3-4 "," fl6 ":"
3-4 to 4-5 grade ",//today's clothing index; "Index": "Hot", "index_d": "Hot weather, suggest a blouse, short skirts, shorts, thin t-shirts, such as cool summer clothing." ",///48-hour dressing Index" index48 ":" Hot "," index48_d ":" Hot weather, suggest a blouse, short skirts, shorts, thin t-shirts, such as cool summer clothing. " ",//UV and 48-hour Ultraviolet" INDEX_UV ":" Medium "," INDEX48_UV ":" Medium ",//Car wash index" INDEX_XC ":" Appropriate ",//Tourism Index" INDEX_TR ":" Less appropriate ",///Comfort Index" Index_co " : "Very uncomfortable", "st1": "A", "St2": "", "St3": "", "St4": "", "St5": "", "St6": "27",//Morning exercise Index "INDEX_CL": "More appropriate",//Drying index "index_"
LS ": Suitable",//Allergy Index "INDEX_AG": "Not easy to send"}
We can get the weather data for the corresponding city by parsing the JSON.
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 is an urban correspondence file weather_cityid.php, formatted as follows:
<?php
$weather _cityid = Array ("Beijing" => "101010100", "Shanghai" => "101020100", "Suzhou" => "101190401");
? >
According to the incoming city name, get the city code, if not empty, then call the Chinese Weather Network API to query, return the JSON format data, then parse and return data, if empty, return null value.
V. Organization reply Message Form
To determine whether the returned data is NULL, if NULL, then $contentStr = "Sorry, did not find \" ". $str _key." \ "Weather Information!" ";
If the returned data is not empty, then:
$CONTENTSTR = "". $data->weatherinfo->city. " Weather forecast "\ n". $data->weatherinfo->date_y. " ". $data->weatherinfo->fchh." When you publish "." \ n \ nthe weather \ n ". $data->weatherinfo->weather1." ". $data->weatherinfo->temp1." ". $data->weatherinfo->wind1." \ n \ na warm hint: ". $data->weatherinfo->index_d." \ n \ n "$data->weatherinfo->weather2." ". $data->weatherinfo->temp2." ". $data->weatherinfo->wind2." \ n \ \ \ \ \ \ \ \ \ $data->weatherinfo->weather3. " ". $data->weatherinfo->temp3." ". $data->weatherinfo->wind3;
Description:
$data->weatherinfo->city//Get city name, here is Suzhou
$data->weatherinfo->date_y//Get the date, here is 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
Weather2, Temp2, Wind2, respectively, represent the weather for tomorrow, the temperature and wind speed, and so on.
\ n//= line Wrap
VI. Testing
Seven, complete code
<?php/** * WeChat PHP Test * *//define Your token ("define", "token");
$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 is due to the different $POSTSTR = $GLOBAL
s["Http_raw_post_data"]; Extract post Data if (!empty ($POSTSTR)) {$POSTOBJ = simplexml_load_string ($postStr, ' simplexmlelement ', LIBX
Ml_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
The Public Function Handletext ($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, -2,2, "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." DaysGas forecast "\ n". $data->weatherinfo->date_y. " ". $data->weatherinfo->fchh." When you publish "." \ n \ nthe weather \ n ". $data->weatherinfo->weather1." ". $data->weatherinfo->temp1." ". $data->weatherinfo->wind1." \ n \ na warm hint: ". $data->weatherinfo->index_d." \ n \ n "$data->weatherinfo->weather2." ". $data->weatherinfo->temp2." ". $data->weatherinfo->wind2." \ n \ \ \ \ \ \ \ \ \ $data->weatherinfo->weather3. " ". $data->weatherinfo->temp3."
". $data->weatherinfo->wind3; } else {$contentStr = "Thank you for your interest in" Zhuo Jin Suzhou "." \ n "." Micro-signal: Zhuojinsz "." \ n "." Excellent splendid, Suzhou City, we provide you with Suzhou Local life guide, Suzhou Related information inquiries, do the best Suzhou Micro-trust platform. "." \ n "." The current platform features are as follows: "." \ n "." "1" Check the weather, such as input: Suzhou weather "." \ n "." "2" check public transport, such as input: Suzhou bus 178 "." \ n "." "3" translation, such as input: translation I love You "." \ n "." "4" Suzhou information inquiries, such as input: Suzhou Guan Qian Jie "." \ n "."
More content, please look forward to ... ";
$RESULTSTR = sprintf ($TEXTTPL, $fromUsername, $toUsername, $time, $msgType, $CONTENTSTR);
Echo $resultStr;
}else{echo "Input something ...";
The Public Function handleevent ($object) {$contentStr = ""; Switch ($object->event) {case "subscribe": $CONTENTSTR = "Thank you for your concern" Zhuo Jin Suzhou "." \ n "." Micro-signal: Zhuojinsz "." \ n "." Excellent splendid, Suzhou City, we provide you with Suzhou Local life guide, Suzhou Related information inquiries, do the best Suzhou Micro-trust platform. "." \ n "." The current platform features are as follows: "." \ n "." "1" Check the weather, such as input: Suzhou weather "." \ n "." "2" check public transport, such as input: Suzhou bus 178 "." \ n "." "3" translation, such as input: translation I love You "." \ n "." "4" Suzhou information inquiries, such as input: Suzhou Guan Qian Jie "." \ n "."
More content, please look forward to ... ";
Break
Default: $contentStr = "Unknow Event:". $object->event;
Break
$RESULTSTR = $this->responsetext ($object, $CONTENTSTR);
return $resultStr; The 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;
The 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;
}}}?>
About the city correspondence document Weather_cityid.php, now updated to 2,564 cities, will continue to increase, please go to the official network disk Http://pan.baidu.com/s/1gfcBX6N download it.
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.