PHP WeChat public platform Development-weather forecast function Development _php Tutorial

Source: Internet
Author: User
Tags cdata

"PHP Public Platform Development Series"

01. Configure the interface
02. Public Platform Sample Code analysis
03. Subscription event (SUBSCRIBE) processing
04. Simple Reply Function development
05.API Weather forecast Function development


This address: http://www.phpchina.com/archives/view-43387-1.html
This series by Phpchina invited author @david_tang feeds, reprint please indicate the author information and this article address.

First, Introduction

The previous articles on the PHP public platform for the opening and simple use of a simple introduction, but did not involve the actual use of the problem, such as weather inquiries, bus inquiries, express inquiries. The next few articles will be on the actual life will be used in some of the features of the development to explain, for the reader's reference.

This article will be a daily concern for the development of the weather query, for example, the user sent the message "Suzhou Weather" will return to Suzhou real-time weather conditions, as well as the next two days or even the next five days of weather conditions.

Second, the Thinking analysis

First to the user sent over 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 Chinese Weather Network (http://www.weather.com.cn) provided by the Open API to the relevant regional weather query.

Three, the keyword judgment and the region reads

The format of the message sent by the user to inquire about the weather is fixed, i.e. "region + weather", so the first two words are intercepted to determine whether it is the "weather" keyword.

Use PHP function Mb_substr () intercept, about the use of this function:

Mb_substr-gets a partial string mb_substr (string $str, int $start [, int $length [, String $encoding]) Description: based on the number of characters Performs a multi-byte secure substr () operation. The position is counted from the beginning of the STR position. The position of the first character is 0. The position of the second character is 1, and so on. parameter:str extracts a substring from the string. The position of the first character to be used in the STARTSTR. Positive, starting at the specified position at the beginning of the string, negative, starting at the specified position at the end of the string, and the maximum number of characters to use in the LENGTHSTR. A positive number, starting at start, includes a maximum length character, and the length character at the end of the string, negative, is omitted (if Start is negative, it starts with the string). The encodingencoding parameter is a character encoding. If omitted, the internal character encoding is used. return value:the MB_SUBSTR () function returns the portion specified in 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 the "weather" keyword.

The following area is extracted, or the MB_SUBSTR () function is used.

$str _key = Mb_substr ($keyword, 0,-2, "UTF-8");

From the beginning of the message, truncate the end of the two characters (weather), the region is the keyword.

It then makes the judgment and then calls the function to query the weather data.

if ($str = = ' Weather ' &&!empty ($str _key)) {     //Call Function query weather data}

Iv. Call the weather () function query

We are calling the weather API interface provided by China National Weather Bureau, interface address: http://m.weather.com.cn/data/101190401.html

The number in the URL refers to the city's number 101190401 (Suzhou), and the other city correspondence will be provided below.

The interface returns information in a comprehensive format and is provided in JSON format as follows:

{"Weatherinfo": {//basic information; " City ":" Suzhou "," city_en ":" Suzhou "," date_y ":" July 9, 2013 "," Date ":" "," Week ":" Tuesday "," Fchh ":" 101190401 "," Cityid ":" + ",// 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 ":" Sunny Turn Cloudy "," Weather2 ":" Sunny Turn Cloudy "," Weather3 ":" Sunny Turn Cloudy "," weather4 ":" Cloudy "," Weather5 ":" Thundershowers to Moderate Rain "," Weather6 ":" Thunderstorm Turn cloudy ",/ /Weather Description Picture serial number "IMG1": "0", "Img2": "1", "IMG3": "0", "IMG4": "1", "Img5": "0", "Img6": "1", "Img7": "", "Img8": "1", " Img10 ":" 8 "," Img11 ":" 4 "," Img12 ":" 1 ",//Picture name;" Img_single ":" 1 "," Img_title1 ":" Sunny "," img_title2 ":" Cloudy "," Img_title3 ":" Sunny "," img_title4 ":" Cloudy "," img_title5 ":" Sunny "," img_ Title6 ":" Cloudy "," Img_title7 ":" Cloudy "," Img_title8 ":" Cloudy "," img_title9 ":" Thunderstorm "," Img_title10 ":" Cloudy "," Img_title11 ":" Thunderstorm "," Img_title12 ":" Cloudy "," Img_title_single ":" Cloudy ",//wind speed description" Wind1 ":" Southwest Wind Level 3-4 "," Wind2 ":" Southwest Wind 3-4 "," Wind3 ":" Southeast Wind 3-4 "," Wind4 ": "Southeast wind level 3-4 to Level 4-5", "Wind5":" Southeast Wind level 4-5 to southwest wind 3-4 "," Wind6 ":" Southwest wind 3-4 level to 4-5 ",//wind speed level description" fx1 ":" Southwest Wind "," FX2 ":" Southwest Wind "," FL1 ":" 3-4 Level "," FL2 ":" 3-4 Level "," FL3 ":" Level 3-4 "," Fl4 ":" 3-4 level to 4-5 level "," FL5 ":" 4-5 level to 3-4 level "," fl6 ":" 3-4 level to 4-5 level ",//Today clothing index; Index ": Hot", "index_d": "Hot weather, suggest a blouse, short skirts, shorts, thin t-shirts and other cool summer clothing." ",//48 hour clothing Index" index48 ":" Hot "," index48_d ":" Hot weather, suggest a blouse, short skirts, shorts, thin t-shirts and other cool summer clothing. " ",//UV and 48 hours UV" INDEX_UV ":" Medium "," INDEX48_UV ":" Medium ",//Car wash index" INDEX_XC ":" Suitable ",//Tourism Index" INDEX_TR ":" More unfavorable ",//Comfort index" Index_co " : "Very uncomfortable", "St1": "", "St2": "27", "ST3": "", "" "," St4 ":" "," St5 ":" "," St6 ":" ",//Morning exercise Index" INDEX_CL ":" More appropriate ",//Drying index" index_ LS ":" suitable ",//Allergy Index" INDEX_AG ":" Not easy to send "}}

We can get 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;}    }

This include a city correspondence file weather_cityid.php, in the following format:

 
  "101010100", "shanghai" = "101020100", "suzhou" = "101190401"); >

According to the city name passed in, the city code is obtained, if not empty, the API of China Weather NET is called to query, return the data in JSON format, parse and return the data, if empty, return null value.

V. Organization reply Message Form

Determines whether the returned data is empty, if empty, $contentStr = "Sorry, no \" ". $str _key." \ "Weather info! ";

If the returned data is not empty, then:

$CONTENTSTR = "". $data->weatherinfo->city. " The weather forecast is "\ n". $data->weatherinfo->date_y. " ". $data->weatherinfo->fchh." When publishing "." \ n \ nthe real-time weather \ n ". $data->weatherinfo->weather1." ". $data->weatherinfo->temp1." ". $data->weatherinfo->wind1." \ n: ". $data->weatherinfo->index_d." \ nyou tomorrow, "$data->weatherinfo->weather2." ". $data->weatherinfo->temp2." ". $data->weatherinfo->wind2." \ nthe day after tomorrow, "$data->weatherinfo->weather3." ". $data->weatherinfo->temp3." ". $data->weatherinfo->wind3;

Description

$data->weatherinfo->city//Get city name, here is Suzhou

$data->weatherinfo->date_y//Get date, this 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 of tomorrow, the temperature and wind speed, and so on.

\ n//means line break

VI. Testing

Seven, 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 is due to the different environments $po          STSTR = $GLOBALS ["Http_raw_post_data"]; Extract post Data if (!empty ($POSTSTR)) {$POSTOBJ = simplexml_load_string ($postS                TR, ' 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, -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 info!                "; } else {$contentStr = "". $data->weatherinfo->city. " The weather forecast is "\ n". $data->weatherinfo->date_y. " ". $data->weatherinfo->fchh." When publishing "." \ n \ nthe real-time weather \ n ". $data->weatherinfo->weather1." ". $data->weatherinfo->temp1." ". $data->weatherinfo->wind1." \ n: ". $data->weatherinfo->index_d." \ nyou tomorrow, "$data->weatherinfo->weather2." ". $data->weatherinfo->temp2." ". $data->weatherinfo->wind2." \ nthe day after tomorrow, "$data->weatherinfo->weather3." ". $data->weatherinfo->temp3." ". $data->weatherinfo->wind3; }} else {$contentStr = "Thank you for your interest in" Zhuo Jin Suzhou "." \ n "." Number: Zhuojinsz "." \ n "." Excellent splendid, famous city of Suzhou, we provide you with Suzhou Local life guide, Suzhou Related information query, do the best Suzhou platform. "." \ n "." The current platform features are as follows: "." \ n "." "1" Check the weather, such as enter: Suzhou Weather "." \ n "." "2" Check bus, such as input: Suzhou bus 178 "." \ n "." "3" translation, such as input: translation I love You "." \ n "." "4" Suzhou information query, such as input: Suzhou Guan Qian Street. \ n "."            For more information, please look forward to ... ";            } $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 interest in" Zhuo Jin Suzhou "." \ n "." Number: Zhuojinsz "." \ n "." Excellent splendid, famous city of Suzhou, we provide you with Suzhou Local life guide, Suzhou Related information query, do the best Suzhou platform. "." \ n "." The current platform features are as follows: "." \ n "." "1" Check the weather, such as enter: Suzhou Weather "." \ n "." "2" Check bus, such as input: Suzhou bus 178 "." \ n "." "3" translation, such as input: translation I love You "." \ n "." "4" Suzhou information query, such as input: Suzhou Guan Qian Street. \ n "."                For more information, please look forward to ... ";            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; }}}?>

About the city correspondence file weather_cityid.php, currently updated to 2,564 cities, will continue to increase, please go to the music to enjoy the official forum (url:http://www.joythink.net/) download it.



=========================================================

Phpchina Platform opened!

Search Phpchina", click the Follow button, you can get PPC for you to push the latest and most professional industry information, more special section for you to offer

"PPC Mining": The story of the classic product and product people is not timed.
"PPC Foreign Language": Sharing a foreign translation article at irregular intervals
"PPC Quiz": Daily focus on answering questions from users
"Coder Radio Pro": Unscheduled broadcasts

http://www.bkjia.com/PHPjc/739144.html www.bkjia.com true http://www.bkjia.com/PHPjc/739144.html techarticle "PHP Public Platform Development Series" 01. Configure interface 02. Public Platform Sample Code Analysis 03. Subscription event (subscribe) processing 04. Simple reply Function developing 05.API weather forecast ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.