search
HomeBackend DevelopmentPHP TutorialExample 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&#63;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

<&#63;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  
&#63;>  

8. Check whether it contains Chinese

<&#63; 
$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 "错误输入"; 
} 
&#63;> 

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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1049136.htmlTechArticleExample of using PHP to develop WeChat public platform, php public 1. Connection to SAE database. The host name and port are required and will be the same for future use. @ $db = new mysqli(SAE_MYSQL_HOS...
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.