search
HomeBackend DevelopmentPHP TutorialWeChat public platform development (5) Weather forecast function development_PHP tutorial


The previous articles have briefly explained the opening and simple use of the WeChat public platform Introduction, but they do not involve problems in actual use, such as weather query, bus query, express delivery query, 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 next two days or even the next five days. weather conditions.

First of all, we need to judge the message sent by the user to determine whether the message contains the "weather" key If it contains, you need to continue to extract regional information, and then query the relevant regional weather through the open API provided by China Weather Network (http://www.weather.com.cn).

The format of the message sent by the user to inquire about the weather is fixed, that is, “ Region + weather", so first intercept the last two words to determine whether they are the "weather" keyword.

Use the PHP function mb_substr() to intercept. About the usage of this function:

<span mb_substr &mdash; 获取字符串的部分

  <span string mb_substr ( <span string <span $str , int <span $start [, int <span $length [, 
<span string <span $encoding<span  ]] )根据字符数执行一个多字节安全的 <span substr() 操作。 位置是从 str 的开始位置进行计数。
 第一个字符的位置是 0。第二个字符的位置是 1<span ,以此类推。str
从该 <span string<span  中提取子字符串。

start
str 中要使用的第一个字符的位置。
正数 -> 从字符串开头指定位置开始;
负数 -> 从字符串结尾指定位置开始;
length
str 中要使用的最大字符数。
正数 -> 从 start <span 处开始最多包括 length 个字符;
负数 -> string 末尾处的 length 个字符将会被漏掉(若 start 是负数则从字符串开头算起)。
encoding
encoding 参数为字符编码。如果省略,则使用内部字符编码。mb_substr() 函数根据 start 和 length 
参数返回 str 中指定的部分。

$str = mb_substr($keyword,-2,2,"UTF-8");

Start from the second character from the end of the message, intercept two characters, and then determine whether it is the "weather" keyword.

For region extraction, still use the mb_substr() function.

$str_key = mb_substr($keyword,0,-2,"UTF-8");

Start from the beginning of the message and truncate the last two characters (weather), you have Region keyword.

Then make a judgment and then call the function to query the weather data.

<span if(<span $str == &#39;天气&#39; && !empty($str_key)<span )
{
     <span //调用函数查询天气数据}

What we call here is the weather forecast API interface provided by the China National Meteorological Administration , interface address: http://m.weather.com.cn/data/101190401.html

The numbers in the URL refer to the city number 101190401 (Suzhou), and the corresponding relationships of other cities 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:

<span {"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":"不易发"}}

weather() function is as follows:

<span private <span function weather(<span $n<span ){<span include("weather_cityId.php"<span );
<span $c_name=<span $weather_cityId[<span $n<span ];<span if(!<span empty(<span $c_name<span )){
<span $json=<span file_get_contents("http://m.weather.com.cn/data/".<span $c_name.".html"<span );
<span return json_decode(<span $json<span );
    } <span else<span  {<span return <span null<span ;
    }
}

A city correspondence file weather_cityId.php is included here, the format is as follows:

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

According to the incoming city Name, get the city code. If it is not empty, call the API of China Weather Network for query, return data in json format, and then parse and return the data. If it is empty, return a null value.

Determine whether the returned data is empty. If it is empty, then $contentStr = "Sorry, no check Weather information to "".$str_key.""! ";

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;

Explanation:

weatherinfo->city //Get the city name, here is Suzhou

weatherinfo->date_y //Get the date, here is July 9, 2013

weatherinfo-> ;fchh //Data release time

weatherinfo->weather1 //Real-time weather

weatherinfo->temp1 //Real-time temperature

weatherinfo->wind1 // Real-time wind direction and wind speed

weatherinfo->index_d //Clothing index

< ;span 7. Complete code

<?<span php
<span /*<span *
  * wechat php test
  <span */<span //<span define your token<span define("TOKEN", "zhuojin"<span );
<span $wechatObj = <span new<span  wechatCallbackapiTest();
<span $wechatObj-><span responseMsg();
<span //valid();<span class<span  wechatCallbackapiTest
{<span /*checkSignature()){
            echo $echoStr;
            exit;
        }
    }<span */<span public <span function<span  responseMsg()
    {<span //<span get post data, May be due to the different environments<span $postStr = 
    <span $GLOBALS["HTTP_RAW_POST_DATA"<span ];

          <span //<span extract post data<span if (!<span empty(<span $postStr<span )){
                
                  <span $postObj = <span simplexml_load_string(<span $postStr, &#39;SimpleXMLElement&#39;,
                  <span  LIBXML_NOCDATA);<span $RX_TYPE = <span trim(<span $postObj-><span MsgType);
                  <span switch(<span $RX_TYPE<span )
                {<span case "text":<span $resultStr = <span $this->handleText(<span $postObj<span );
                <span break<span ;<span case "event":<span $resultStr = <span $this->handleEvent(
                <span $postObj<span );<span break<span ;<span default:<span $resultStr = "Unknow msg type: ".
                <span $RX_TYPE<span ;<span break<span ;
                }<span echo <span $resultStr<span ;
        }<span else<span  {<span echo ""<span ;<span exit<span ;
        }
    }<span public <span function handleText(<span $postObj<span )
    {<span $fromUsername = <span $postObj-><span FromUserName;<span $toUsername = <span $postObj->
    <span ToUserName;<span $keyword = <span trim(<span $postObj-><span Content);
    <span $time = <span time<span ();<span $textTpl = "<span %s0"<span ;             
    <span if(!<span empty( <span $keyword<span  ))
        {<span $msgType = "text"<span ;<span //<span 天气<span $str = mb_substr(<span $keyword,-2,2,"UTF-8"
        <span );<span $str_key = mb_substr(<span $keyword,0,-2,"UTF-8"<span );<span if(<span $str == &#39;天气&#39; && !
        <span empty(<span $str_key<span )){<span $data = <span $this->weather(<span $str_key<span );
        <span if(<span empty(<span $data-><span weatherinfo)){<span $contentStr = "抱歉,没有查到\"".
        <span $str_key."\"的天气信息!"<span ;
                } <span else<span  {<span $contentStr = "【".<span $data->weatherinfo->city."天气预报】\n".
                <span $data->weatherinfo->date_y." ".<span $data->weatherinfo->fchh."时发布"."\n\n实时天气\n".
                <span $data->weatherinfo->weather1." ".<span $data->weatherinfo->temp1." ".
                <span $data->weatherinfo->wind1."\n\n温馨提示:".<span $data->weatherinfo->index_d."\n\n明天\n".
                <span $data->weatherinfo->weather2." ".<span $data->weatherinfo->temp2." ".
                <span $data->weatherinfo->wind2."\n\n后天\n".<span $data->weatherinfo->weather3." ".
                <span $data->weatherinfo->temp3." ".<span $data->weatherinfo-><span wind3;
                }
            } <span else<span  {<span $contentStr = "感谢您关注【卓锦苏州】"."\n"."微信号:zhuojinsz"."\n".
            "卓越锦绣,名城苏州,我们为您提供苏州本地生活指南,苏州相关信息查询,做最好的苏州微信平台。"."\n".
            "目前平台功能如下:"."\n"."【1】 查天气,如输入:苏州天气"."\n"."
            【2】 查公交,如输入:苏州公交178"."\n"."【3】 翻译,如输入:翻译I love you"."\n"."
            【4】 苏州信息查询,如输入:苏州观前街"."\n"."更多内容,敬请期待..."<span ;
            }<span $resultStr = <span sprintf(<span $textTpl, <span $fromUsername, <span $toUsername, 
            <span $time, <span $msgType, <span $contentStr<span );
            <span echo <span $resultStr<span ;
        }<span else<span {<span echo "Input something..."<span ;
        }
    }<span public <span function handleEvent(<span $object<span )
    {<span $contentStr = ""<span ;<span switch (<span $object-><span Event)
        {<span case "subscribe":<span $contentStr = "感谢您关注【卓锦苏州】"."\n"."微信号:zhuojinsz"."\n"."
        卓越锦绣,名城苏州,我们为您提供苏州本地生活指南,苏州相关信息查询,做最好的苏州微信平台。"."\n"."
        目前平台功能如下:"."\n"."【1】 查天气,如输入:苏州天气"."\n"."
        【2】 查公交,如输入:苏州公交178"."\n"."【3】 翻译,如输入:翻译I love you"."\n"."
        【4】 苏州信息查询,如输入:苏州观前街"."\n"."更多内容,敬请期待..."<span ;<span break<span ;
        <span default :<span $contentStr = "Unknow Event: ".<span $object-><span Event;<span break<span ;
        }<span $resultStr = <span $this->responseText(<span $object, <span $contentStr<span );<span return 
        <span $resultStr<span ;
    }
    <span public <span function responseText(<span $object, <span $content, <span $flag=0<span )
    {<span $textTpl = "<span %s%d"<span ;<span $resultStr = <span sprintf(<span $textTpl, 
    <span $object->FromUserName, <span $object->ToUserName, <span time(), <span $content, <span $flag<span );
    <span return <span $resultStr<span ;
    }<span private <span function weather(<span $n<span ){<span include("weather_cityId.php"<span );
    <span $c_name=<span $weather_cityId[<span $n<span ];<span if(!<span empty(<span $c_name<span )){
    <span $json=<span file_get_contents("http://m.weather.com.cn/data/".<span $c_name.".html"<span );
    <span return json_decode(<span $json<span );
        } <span else<span  {<span return <span null<span ;
        }
    }<span private <span function<span  checkSignature()
    {<span $signature = <span $_GET["signature"<span ];<span $timestamp = <span $_GET["timestamp"<span ];
    <span $nonce = <span $_GET["nonce"<span ];    
                <span $token =<span  TOKEN;<span $tmpArr = <span array(<span $token, <span $timestamp, 
                <span $nonce<span );<span sort(<span $tmpArr<span );<span $tmpStr = <span implode( 
                <span $tmpArr<span  );<span $tmpStr = <span sha1( <span $tmpStr<span  );
        <span if( <span $tmpStr == <span $signature<span  ){<span return <span true<span ;
        }<span else<span {<span return <span false<span ;
        }
    }
}

?>

Regarding the city correspondence file weather_cityId.php, it has been updated to more than 400 cities and will continue to be added in the future. Please go to QQ group 213260412 to download it.

Please followZhuojin Suzhou WeChat public account, Zhuojin Suzhou is developed based on the SAE platform and is developed and tested for mainstream WeChat functions.

You can follow the Zhuojin Suzhou public account to conduct functional testing and obtain new application development.

1. Log in to the WeChat client, friends -> Add friends -> Search number -> zhuojinsz, find and follow.

2. Scan the QR code:

Zhuojin Suzhou Function list.


The above is the content of WeChat public platform development (5) Weather forecast function development_PHP tutorial. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!

http://www.bkjia.com/PHPjc/440409.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/440409.htmlTechArticle’s previous articles discussed the opening and closing of the WeChat public platform Simple use is briefly introduced, but it does not involve problems in actual use, such as weather query, bus query, express query...


Statement
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
What are some common problems that can cause PHP sessions to fail?What are some common problems that can cause PHP sessions to fail?Apr 25, 2025 am 12:16 AM

Reasons for PHPSession failure include configuration errors, cookie issues, and session expiration. 1. Configuration error: Check and set the correct session.save_path. 2.Cookie problem: Make sure the cookie is set correctly. 3.Session expires: Adjust session.gc_maxlifetime value to extend session time.

How do you debug session-related issues in PHP?How do you debug session-related issues in PHP?Apr 25, 2025 am 12:12 AM

Methods to debug session problems in PHP include: 1. Check whether the session is started correctly; 2. Verify the delivery of the session ID; 3. Check the storage and reading of session data; 4. Check the server configuration. By outputting session ID and data, viewing session file content, etc., you can effectively diagnose and solve session-related problems.

What happens if session_start() is called multiple times?What happens if session_start() is called multiple times?Apr 25, 2025 am 12:06 AM

Multiple calls to session_start() will result in warning messages and possible data overwrites. 1) PHP will issue a warning, prompting that the session has been started. 2) It may cause unexpected overwriting of session data. 3) Use session_status() to check the session status to avoid repeated calls.

How do you configure the session lifetime in PHP?How do you configure the session lifetime in PHP?Apr 25, 2025 am 12:05 AM

Configuring the session lifecycle in PHP can be achieved by setting session.gc_maxlifetime and session.cookie_lifetime. 1) session.gc_maxlifetime controls the survival time of server-side session data, 2) session.cookie_lifetime controls the life cycle of client cookies. When set to 0, the cookie expires when the browser is closed.

What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version