


[PHP WeChat public platform development series]
01. Configure WeChat interface
02. Public platform sample code analysis
03. Subscription event (subscribe) processing
04. Development of simple reply function
05.API weather forecast function development
URL of this article: http://www.phpchina.com/archives/view-43387-1.html
This series is contributed by PHPChina's specially invited author @David_Tang. Please indicate the author's information and the address of this article when reprinting.
1. Introduction
The previous articles gave a brief introduction to the opening and simple use of the PHP WeChat public platform, but they did not involve problems in actual use, such as weather inquiries, bus inquiries, express delivery inquiries, etc. The next few articles will develop and explain some functions that are often used in real life for readers' reference.
This article will develop weather queries that everyone cares about every day. For example, if a user sends a message "Suzhou Weather", the real-time weather conditions in Suzhou will be returned, as well as the weather conditions for the next two days or even the next five days.
2. Idea analysis
First, we need to judge the message sent by the user to determine whether the message contains the "weather" keyword. If it does, we need to continue to extract the regional information, and then use the China Weather Network (http://www.weather.com.cn ) provides an open API for weather queries in related areas.
3. Keyword judgment and region reading
The format of the message sent by the user to check the weather is fixed, that is, "region + weather", so first intercept the last two words to determine whether it is the "weather" keyword.
Use the PHP function mb_substr() to intercept. Regarding the usage of this function:

mb_substr — 获取字符串的部分 string mb_substr ( string $str , int $start [, int $length [, string $encoding ]] ) <strong>说明:</strong>根据字符数执行一个多字节安全的 substr() 操作。 位置是从 str 的开始位置进行计数。 第一个字符的位置是 0。第二个字符的位置是 1,以此类推。 <strong>参数:</strong> str 从该 string 中提取子字符串。 start str 中要使用的第一个字符的位置。 正数 -> 从字符串开头指定位置开始; 负数 -> 从字符串结尾指定位置开始; length str 中要使用的最大字符数。 正数 -> 从 start 处开始最多包括 length 个字符; 负数 -> string 末尾处的 length 个字符将会被漏掉(若 start 是负数则从字符串开头算起)。 encoding encoding 参数为字符编码。如果省略,则使用内部字符编码。 <strong>返回值:</strong> mb_substr() 函数根据 start 和 length 参数返回 str 中指定的部分。

$str = mb_substr($keyword,-2,2,"UTF-8");
Start intercepting the second character from the end of the message, intercept two characters, and then determine whether it is the "weather" keyword.
Next, for region extraction, we still use the mb_substr() function.
$str_key = mb_substr($keyword,0,-2,"UTF-8");
Start at the beginning of the message and truncate the last two characters (weather) to obtain the region keyword.
Then make a judgment and then call the function to query the weather data.
if($str == '天气' && !empty($str_key)) { //调用函数查询天气数据 }
4. Call weather() function query
What we are calling here is the weather forecast API interface provided by the China National Meteorological Administration. The interface address is: http://m.weather.com.cn/data/101190401.html
The numbers in the URL refer to the city number 101190401 (Suzhou), and other city correspondences will be provided below.
The information returned by this interface is relatively comprehensive and is also provided in json format. The format is as follows:

{"weatherinfo":{ //基本信息; "city":"苏州","city_en":"suzhou", "date_y":"2013年7月9日","date":"","week":"星期二","fchh":"18","cityid":"101190401", //摄氏温度 "temp1":"30℃~37℃", "temp2":"30℃~37℃", "temp3":"29℃~35℃", "temp4":"27℃~33℃", "temp5":"27℃~31℃", "temp6":"27℃~35℃", //华氏温度; "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℉", //天气描述; "weather1":"晴转多云", "weather2":"晴转多云", "weather3":"晴转多云", "weather4":"多云", "weather5":"雷阵雨转中雨", "weather6":"雷阵雨转多云", //天气描述图片序号 "img1":"0", "img2":"1", "img3":"0", "img4":"1", "img5":"0", "img6":"1", "img7":"1", "img8":"99", "img9":"4", "img10":"8", "img11":"4", "img12":"1", //图片名称; "img_single":"1", "img_title1":"晴", "img_title2":"多云", "img_title3":"晴", "img_title4":"多云", "img_title5":"晴", "img_title6":"多云", "img_title7":"多云", "img_title8":"多云", "img_title9":"雷阵雨", "img_title10":"中雨", "img_title11":"雷阵雨", "img_title12":"多云", "img_title_single":"多云", //风速描述 "wind1":"西南风3-4级", "wind2":"西南风3-4级", "wind3":"东南风3-4级", "wind4":"东南风3-4级转4-5级", "wind5":"东南风4-5级转西南风3-4级", "wind6":"西南风3-4级转4-5级", //风速级别描述 "fx1":"西南风", "fx2":"西南风", "fl1":"3-4级", "fl2":"3-4级", "fl3":"3-4级", "fl4":"3-4级转4-5级", "fl5":"4-5级转3-4级", "fl6":"3-4级转4-5级", //今日穿衣指数; "index":"炎热", "index_d":"天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。", //48小时穿衣指数 "index48":"炎热", "index48_d":"天气炎热,建议着短衫、短裙、短裤、薄型T恤衫等清凉夏季服装。", //紫外线及48小时紫外线 "index_uv":"中等", "index48_uv":"中等", //洗车指数 "index_xc":"适宜", //旅游指数 "index_tr":"较不宜", //舒适指数 "index_co":"很不舒适", "st1":"36", "st2":"28", "st3":"36", "st4":"28", "st5":"34", "st6":"27", //晨练指数 "index_cl":"较适宜", //晾晒指数 "index_ls":"适宜", //过敏指数 "index_ag":"不易发"}}

We can obtain the weather data of the corresponding city by parsing 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; } }

A city correspondence file weather_cityId.php is included here, with the following format:
<?php $weather_cityId = array("北京"=>"101010100","上海"=>"101020100","苏州"=>"101190401"); ?>
According to the incoming city name, the city code is obtained. If it is not empty, the API of China Weather Network is called to query, and the data in json format is returned, and then the data is parsed and returned. If it is empty, a null value is returned.
5. Organizational reply message format
Determine whether the returned data is empty. If it is empty, then $contentStr = "Sorry, no weather information for "".$str_key."" was found!";
If the returned data is not empty, then:
$contentStr = "【".$data->weatherinfo->city."天气预报】\n".$data->weatherinfo->date_y." ".$data->weatherinfo->fchh."时发布"."\n\n实时天气\n".$data->weatherinfo->weather1." ".$data->weatherinfo->temp1." ".$data->weatherinfo->wind1."\n\n温馨提示:".$data->weatherinfo->index_d."\n\n明天\n".$data->weatherinfo->weather2." ".$data->weatherinfo->temp2." ".$data->weatherinfo->wind2."\n\n后天\n".$data->weatherinfo->weather3." ".$data->weatherinfo->temp3." ".$data->weatherinfo->wind3;
Description:
$data->weatherinfo->city //Get the 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 speed
$data->weatherinfo->index_d //Wearing index
weather2, temp2, wind2 respectively represent tomorrow's weather, temperature and wind direction and speed, and so on.
n //Indicates line break
6. Test
七、完整代码

<?php /** * wechat php test */ //define your token define("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 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 = "<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"; //天气 $str = mb_substr($keyword,-2,2,"UTF-8"); $str_key = mb_substr($keyword,0,-2,"UTF-8"); if($str == '天气' && !empty($str_key)){ $data = $this->weather($str_key); if(empty($data->weatherinfo)){ $contentStr = "抱歉,没有查到\"".$str_key."\"的天气信息!"; } else { $contentStr = "【".$data->weatherinfo->city."天气预报】\n".$data->weatherinfo->date_y." ".$data->weatherinfo->fchh."时发布"."\n\n实时天气\n".$data->weatherinfo->weather1." ".$data->weatherinfo->temp1." ".$data->weatherinfo->wind1."\n\n温馨提示:".$data->weatherinfo->index_d."\n\n明天\n".$data->weatherinfo->weather2." ".$data->weatherinfo->temp2." ".$data->weatherinfo->wind2."\n\n后天\n".$data->weatherinfo->weather3." ".$data->weatherinfo->temp3." ".$data->weatherinfo->wind3; } } else { $contentStr = "感谢您关注【卓锦苏州】"."\n"."微信号:zhuojinsz"."\n"."卓越锦绣,名城苏州,我们为您提供苏州本地生活指南,苏州相关信息查询,做最好的苏州微信平台。"."\n"."目前平台功能如下:"."\n"."【1】 查天气,如输入:苏州天气"."\n"."【2】 查公交,如输入:苏州公交178"."\n"."【3】 翻译,如输入:翻译I love you"."\n"."【4】 苏州信息查询,如输入:苏州观前街"."\n"."更多内容,敬请期待..."; } $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 = "感谢您关注【卓锦苏州】"."\n"."微信号:zhuojinsz"."\n"."卓越锦绣,名城苏州,我们为您提供苏州本地生活指南,苏州相关信息查询,做最好的苏州微信平台。"."\n"."目前平台功能如下:"."\n"."【1】 查天气,如输入:苏州天气"."\n"."【2】 查公交,如输入:苏州公交178"."\n"."【3】 翻译,如输入:翻译I love you"."\n"."【4】 苏州信息查询,如输入:苏州观前街"."\n"."更多内容,敬请期待..."; 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; } } } ?>

关于城市对应关系文件 weather_cityId.php,目前更新到了2564个城市,以后还会继续增加,请到 乐思乐享 官方论坛(URL:http://www.joythink.net/)下载吧。
=========================================================
PHPChina微信平台开通啦!
微信搜索“PHPChina”,点击关注按钮,即可获得PPC为您推送的最新最专业的业界信息,更有更多专题栏目为您献上
【PPC挖掘】: 不定时为您献上经典产品与产品人的故事。
【PPC外文】: 不定时分享一篇外文翻译文章
【PPC问答】: 每日集中回复关注用户的提问
【Coder Radio Pro】:不定期广播节目


php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Atom editor mac version download
The most popular open source editor

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
