Example of using PHP for WeChat public platform development, php public _ PHP Tutorial

Source: Internet
Author: User
Example of using PHP for public platform development: php public. Example of using PHP for public platform development: connection of php public 1. SAE database. The host name and port must be used in the future. @ $ Dbnewmysqli (example of using PHP for public platform development by SAE_MYSQL_HOS, php public

1. connection to the SAE database.

The host name and port must be used in the future.

@ $ Db = new mysqli (SAE_MYSQL_HOST_M. ':'. SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS, 'Your application name ');

2. XML processing.

All messages sent are in XML format, and the messages you return must also be in XML format. Extract data from XML. SimpleXML is powerful and easy to use. How about packaging XML messages? Save the message template as a string and use sprintf to format the output.

Parse server POST data:

// ---------- Receive data ---------- // $ postStr = $ GLOBALS ["HTTP_RAW_POST_DATA"]; // Get POST data // Parse post xml data with SimpleXML $ postObj = simplexml_load_string ($ postStr, 'simplexmlelement', LIBXML_NOCDATA); $ fromUsername = $ postObj-> FromUserName; // Obtain the sender's account (OpenID) $ toUsername = $ postObj-> ToUserName; // Obtain the recipient's account $ msgType = $ postObj-> MsgType; // message content

Return text message:

Function sendText ($ to, $ from, $ content, $ time) {// return message template $ textTpl ="
    
  %s
     
  %s
     
  
   
% S
     
  %s
     
  %s
     
  
   
0
     
 "; // Format the message template $ msgType =" text "; $ time = time (); $ resultStr = sprintf ($ textTpl, $ to, $ from, $ time, $ msgType, $ content); echo $ resultStr ;}

3. call an API.

There are many API interfaces on the Internet, such as Baidu translation, Youdao translation, and weather forecast. you can directly use file_get_contents or curl to call the interfaces, then parse the returned data in xml or json format. SimpleXML and json_decode are convenient for processing. To capture API content, use the re-encapsulated function:

Function my_get_file_contents ($ url) {if (function_exists ('File _ get_contents ') {$ file_contents = file_get_contents ($ url );} else {// initialize a cURL object $ ch = curl_init (); $ timeout = 5; // Set the URL to be crawled curl_setopt ($ ch, CURLOPT_URL, $ url ); // Set the cURL parameter. The result must be saved to the string or output to the screen. curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); // The waiting time before the connection is initiated, if it is set to 0, you can wait for curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout) infinitely; // run cURL to request the webpage $ file_contents = curl_exec ($ ch ); // curl_close ($ ch);} return $ file_contents;} Baidu translation API calls: function baiduDic ($ word, $ from = "auto ", $ to = "auto") {// urlencode the text to be translated first $ word_code = urlencode ($ word ); // registered API Key $ appid = "yourAPIkey"; // Generate the url get address for the translation API $ 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. calculate the longitude and latitude of "nearby.

Use the following model to calculate the latitude and longitude of a square. Haversin formula is used.

// $ EARTH_RADIUS = 6371; // Earth radius, the average radius is 6371 km/***, and the four points of the square with a certain distance around a certain latitude and longitude are calculated ** @ param lng float longitude * @ param lat float latitude * @ param distance float radius of the circle where the point is located, this circle is tangent to this square. the default value is 0.5 km * @ return array coordinate of the longitude and latitude of the four points of the square */function returnSquarePoint ($ lng, $ lat, $ distance = 0.5) {$ EARTH_RADIUS = 6371; $ dlng = 2 * asin (sin ($ distance/(2 * $ EARTH_RADIUS)/cos (deg 2rad ($ 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);} sort the query results in descending chronological order. The message is a table in the database, the location_X is the dimension, and the location_Y is the longitude: // use this function to calculate the result and bring it into the SQL query. $ 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.

It must be 6-20 letters. if the match is true, true is returned. otherwise, false is returned. Regular expressions are used for matching:

function inputCheck($word) {   if(preg_match("/^[0-9a-zA-Z]{6,20}$/",$word))   {     return true;   }   return false; } 

6. obtain a substring from a string containing Chinese characters.Use mb_substr to intercept the http://www.php.net/manual/zh/function.mb-substr.php

7. check the length of a string mixed with Chinese and English

<? Php $ str = "Sanzhi sunchis Development Network"; echo strlen ($ str )."
"; // Result: 22 echo mb_strlen ($ str," UTF8 ")."
"; // Result: 12 $ strlen = (strlen ($ str) + mb_strlen ($ str," UTF8 ")/2; echo $ strlen; // result: 17?>

8. check for Chinese characters

<? $ Str = "test Chinese"; echo $ str; echo ""; // if (preg_match ("/^ [". chr (0xa1 ). "-". chr (0xff ). "] + $/", $ str )) {// only use GB2312 // if (preg_match ("/^ [\ x7f-\ xff] + $/", $ str) {// Compatible with gb2312, UTF-8 // Determine whether the string is all Chinese if (preg_match ("/[\ x7f-\ xff]/", $ str )) {// check whether the string contains the Chinese echo "correct input";} else {echo "incorrect input";}?>

Double byte character encoding range
1. GBK (GB2312/GB18030)
\ X00-\ xff GBK dubyte encoding range
\ X20-\ x7f ASCII
\ Xa1-\ xff Chinese gb2312
\ X80-\ xff Chinese gbk

2. UTF-8 (Unicode)
\ U4e00-\ u9fa5 Chinese
\ X3130-\ x318F Korean
\ XAC00-\ xD7A3 Korean
\ U0800-\ u4e00 Japanese

9. Use of Jquery Mobile
Official website: http://blog.jquerymobile.com/
It was very painful to write a mobile webpage by myself. CSS debugging was annoying and cross-platform debugging was not good. later I found this library, which was actually much simpler and looked much more beautiful.
However, some new problems are introduced, such as loading CSS and Javascript on the page, because Jquery Mobile loads the page using Ajax by default and does not refresh the entire html, instead, a page is requested. Therefore, the pages of multiple pages are not fully loaded, and CSS and Javascript in the head are not loaded, therefore, one method is to set ajax = false in the link property to indicate that the page is not loaded through Ajax, and the other is to load CSS and Javascript into the page. I will not discuss it here.

10. mobile Web Debugging
At first, every time you debug a page, you have to connect your phone to WIFI to refresh the page! Later, I finally learned how...
Recommend this website: http://www.responsinator.com /? Url = put your webpage url in the input box at the top, and then "Go", you can see that your webpage is displayed on various platforms, even Kindle ..
Of course, Google, which is essential for developers, can also act as a mobile browser for us. press F12 to enter the developer mode and click the setting icon in the lower right corner. you can set the User Agent and Device metrics in Overrides, the results are equally good.

Connection 1. SAE database connection. The host name and port must be used in the future. @ $ Db = new mysqli (SAE_MYSQL_HOS...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.