Home Backend Development PHP Tutorial PHP WeChat public platform development - weather forecast function development_PHP tutorial

PHP WeChat public platform development - weather forecast function development_PHP tutorial

Jul 13, 2016 am 10:36 AM
php WeChat

[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:

PHP WeChat public platform development - weather forecast function development_PHP tutorial
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 中指定的部分。
Copy after login
PHP WeChat public platform development - weather forecast function development_PHP tutorial

$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 == &#39;天气&#39; && !empty($str_key))
{
     //调用函数查询天气数据
}
Copy after login

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:

PHP WeChat public platform development - weather forecast function development_PHP tutorial
{"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":"不易发"}}
Copy after login
PHP WeChat public platform development - weather forecast function development_PHP tutorial

We can obtain the weather data of the corresponding city by parsing JSON.

The weather() function is as follows:

PHP WeChat public platform development - weather forecast function development_PHP tutorial
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;
    }
}
Copy after login
PHP WeChat public platform development - weather forecast function development_PHP tutorial

A city correspondence file weather_cityId.php is included here, with the following format:

<?php
$weather_cityId = array("北京"=>"101010100","上海"=>"101020100","苏州"=>"101190401");
?>
Copy after login

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;
Copy after login

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 public platform development - weather forecast function development_PHP tutorial
<?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, &#39;SimpleXMLElement&#39;, 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 == &#39;天气&#39; && !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;
        }
    }
}

?>
Copy after login
PHP WeChat public platform development - weather forecast function development_PHP tutorial

关于城市对应关系文件 weather_cityId.php,目前更新到了2564个城市,以后还会继续增加,请到 乐思乐享 官方论坛(URL:http://www.joythink.net/)下载吧。
 



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

PHPChina微信平台开通啦!

微信搜索“PHPChina”,点击关注按钮,即可获得PPC为您推送的最新最专业的业界信息,更有更多专题栏目为您献上

【PPC挖掘】: 不定时为您献上经典产品与产品人的故事。
【PPC外文】: 不定时分享一篇外文翻译文章
【PPC问答】: 每日集中回复关注用户的提问
【Coder Radio Pro】:不定期广播节目

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/739144.htmlTechArticle【PHP微信公众平台开发系列】 01.配置微信接口 02.公众平台示例代码分析 03.订阅事件(subscribe)处理 04.简单回复功能开发 05.API天气预报功...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

gateio exchange app old version gateio exchange app old version download channel gateio exchange app old version gateio exchange app old version download channel Mar 04, 2025 pm 11:36 PM

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? Apr 01, 2025 pm 10:48 PM

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

Detailed tutorial on how to buy and sell Binance virtual currency Detailed tutorial on how to buy and sell Binance virtual currency Mar 18, 2025 pm 01:36 PM

This article provides a brief guide to buying and selling of Binance virtual currency updated in 2025, and explains in detail the operation steps of virtual currency transactions on the Binance platform. The guide covers fiat currency purchase USDT, currency transaction purchase of other currencies (such as BTC), and selling operations, including market trading and limit trading. In addition, the guide also specifically reminds key risks such as payment security and network selection for fiat currency transactions, helping users to conduct Binance transactions safely and efficiently. Through this article, you can quickly master the skills of buying and selling virtual currencies on the Binance platform and reduce transaction risks.

See all articles