


Example of using PHP to develop WeChat public platform, php public_PHP tutorial
Example of using PHP for WeChat public platform development, php public
1. Connection to SAE database.
The host name and port are required and will be used in the future.
@ $db = new mysqli(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS,'你的应用名');
2.XML processing.
The message formats sent by WeChat are all in XML format, and the messages you return must also be in XML format. Extract data from XML with SimpleXML, which is powerful and easy to use. What about wrapping it into an XML message? Save the message template as a string, and then use sprintf to format the output.
Parse WeChat server POST data:
//---------- 接 收 数 据 ---------- // $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //获取POST数据 //用SimpleXML解析POST过来的XML数据 $postObj = simplexml_load_string($postStr,'SimpleXMLElement',LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; //获取发送方帐号(OpenID) $toUsername = $postObj->ToUserName; //获取接收方账号 $msgType = $postObj->MsgType; //消息内容
Return text message:
function sendText($to, $from, $content, $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>"; //格式化消息模板 $msgType = "text"; $time = time(); $resultStr = sprintf($textTpl,$to,$from, $time,$msgType,$content); echo $resultStr; }
3. API interface call.
There are many API interfaces on the Internet, such as Baidu Translation, Youdao Translation, Weather Forecast, etc. You can directly use file_get_contents to call the interface, or you can use curl to crawl, and then perform data analysis according to the format of the returned data. It is generally in xml format or json format, and it is very convenient to use SimpleXML and json_decode when processing. For grabbing API content, use the repackaged function:
function my_get_file_contents($url){ if(function_exists('file_get_contents')){ $file_contents = file_get_contents($url); } else { //初始化一个cURL对象 $ch = curl_init(); $timeout = 5; //设置需要抓取的URL curl_setopt ($ch, CURLOPT_URL, $url); //设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); //在发起连接前等待的时间,如果设置为0,则无限等待 curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); //运行cURL,请求网页 $file_contents = curl_exec($ch); //关闭URL请求 curl_close($ch); } return $file_contents; } 百度翻译 API 的调用如下: function baiduDic($word,$from="auto",$to="auto"){ //首先对要翻译的文字进行 urlencode 处理 $word_code=urlencode($word); //注册的API Key $appid="yourAPIkey"; //生成翻译API的URL GET地址 $baidu_url = "http://openapi.baidu.com/public/2.0/bmt/translate?client_id=".$appid."&q=".$word_code."&from=".$from."&to=".$to; $text=json_decode(my_get_file_contents($baidu_url)); $text = $text->trans_result; return $text[0]->dst; }
4. Calculation of “nearby” longitude and latitude.
Use the following model to calculate the latitude and longitude of the square. Use Haversin's formula.
//$EARTH_RADIUS = 6371;//地球半径,平均半径为6371km /** *计算某个经纬度的周围某段距离的正方形的四个点 * *@param lng float 经度 *@param lat float 纬度 *@param distance float 该点所在圆的半径,该圆与此正方形内切,默认值为0.5千米 *@return array 正方形的四个点的经纬度坐标 */ function returnSquarePoint($lng, $lat,$distance = 0.5){ $EARTH_RADIUS = 6371; $dlng = 2 * asin(sin($distance / (2 * $EARTH_RADIUS)) / cos(deg2rad($lat))); $dlng = rad2deg($dlng); $dlat = $distance/$EARTH_RADIUS; $dlat = rad2deg($dlat); return array( 'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng), 'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng), 'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng), 'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng) ); } 将查询结果按时间降序排列,message 为数据库中的一个表,location_X 为维度,location_Y 为经度: //使用此函数计算得到结果后,带入sql查询。 $squares = returnSquarePoint($lng, $lat); $query = "select * from message where location_X != 0 and location_X > ".$squares['right-bottom']['lat']." and location_X< ".$squares['left-top']['lat'] ."and location_Y > ".$squares['left-top']['lng']." and location_Y< ".$squares['right-bottom']['lng'] ."order by time desc";
5. Check the string.
is limited to 6-20 letters. If it matches, it will return true , otherwise it will return false and use regular expressions for matching:
function inputCheck($word) { if(preg_match("/^[0-9a-zA-Z]{6,20}$/",$word)) { return true; } return false; }
6. When extracting the substring from a string containing Chinese characters, use mb_substr to intercept http://www.php.net/manual/zh/function.mb-substr.php
7. Detect the length of mixed Chinese and English strings
<?php $str = "三知sunchis开发网"; echo strlen($str)."<br>"; //结果:22 echo mb_strlen($str,"UTF8")."<br>"; //结果:12 $strlen = (strlen($str)+mb_strlen($str,"UTF8"))/2; echo $strlen; //结果:17 ?>
8. Check whether it contains Chinese
<? $str = "测试中文"; echo $str; echo "<hr>"; //if (preg_match("/^[".chr(0xa1)."-".chr(0xff)."]+$/", $str)) { //只能在GB2312情况下使用 //if (preg_match("/^[\x7f-\xff]+$/", $str)) { //兼容gb2312,utf-8 //判断字符串是否全是中文 if (preg_match("/[\x7f-\xff]/", $str)) { //判断字符串中是否有中文 echo "正确输入"; } else { echo "错误输入"; } ?>
Double-byte character encoding range
1. GBK (GB2312/GB18030)
x00-xff GBK double-byte encoding range
x20-x7f ASCII
xa1-xff Chinese gb2312
x80-xff Chinese gbk
2. UTF-8 (Unicode)
u4e00-u9fa5 中文
x3130-x318F Korean
xAC00-xD7A3 Korean
u0800-u4e00 Japanese
9. Use of Jquery Mobile
Official website: http://blog.jquerymobile.com/
It turns out that writing mobile web pages by yourself is really painful. CSS debugging is all kinds of troublesome and cross-platform is not good. Later I discovered this library. It is much simpler and the interface looks much more beautiful.
However, some new problems have also been introduced, such as the loading of CSS and Javascript in the page. Because Jquery Mobile uses Ajax to load the page by default, it does not refresh the entire html, but only requests a page, so for pages with multiple pages It will not be fully loaded, nor will the CSS and Javascript in the head be loaded, so one method is to set ajax=false in the link's attributes to indicate that the page will not be loaded through Ajax, and the other is to put the loading of CSS and Javascript on the page in. I won’t go into details here.
10. Mobile Web Debugging
At the beginning, every time I debugged a page, I had to connect my phone to WIFI to refresh it, which was simply unbearable! Later I finally learned the lesson...
Recommend this website: http://www.responsinator.com/?url= Put your web page URL in the input box at the top and then "Go", you can see the display effect of your web page on various platforms, even Available on Kindle..
Of course, Google, a must-have for developers, can also act as a mobile browser for us. Press F12 to enter developer mode and click the setting icon in the lower right corner. You can set User Agent and Device metrics in Overrides, and the effect is equally good.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



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,

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 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.

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.

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.

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...

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.

In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.
