


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

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

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

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.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

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.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

The... (splat) operator in PHP is used to unpack function parameters and arrays, improving code simplicity and efficiency. 1) Function parameter unpacking: Pass the array element as a parameter to the function. 2) Array unpacking: Unpack an array into another array or as a function parameter.
