使用PHP进行微信公众平台开发的示例
这篇文章主要介绍了使用PHP进行微信公众平台开发的示例,包括基本的微信平台API调用和XML处理等,需要的朋友可以参考下
1. SAE 数据库的连接。
需要主机名和端口,以后的使用是一样的。
@ $db = new mysqli(SAE_MYSQL_HOST_M.':'.SAE_MYSQL_PORT,SAE_MYSQL_USER,SAE_MYSQL_PASS,'你的应用名');
2.XML 的处理。
微信发送的消息格式都是 XML 格式,你返回的消息也必须是 XML 格式。从 XML 里提取数据,用 SimpleXML,强大又容易使用。包装成 XML 消息呢?把消息模板保存为字符串,然后用 sprintf 进行格式化输出。
解析微信服务器 POST 的数据:
//---------- 接 收 数 据 ---------- // $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; //消息内容
返回文本消息:
function sendText($to, $from, $content, $time)
{
//返回消息模板
$textTpl = "
3. API 接口的调用。
网上有很多 API 接口,如百度翻译,有道翻译,天气预报等,对接口的调用可以直接用 file_get_contents ,也可以用 curl 的方式进行抓取,然后根据返回数据的格式进行数据解析,一般都是 xml 格式或者 json 格式,处理时用 SimpleXML 和 json_decode 是很方便的。对于抓取 API 内容,用重新封装的函数:
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.对 “附近” 的经纬度的计算。
用如下模型,计算正方形的经纬度。采用 Haversin 公式。
//$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']['lng']." and location_Y
5. 对字符串的检查。
限定为 6-20个字母,符合则返回 true ,否则返回 false,采用正则表达式进行匹配:
function inputCheck($word) { if(preg_match("/^[0-9a-zA-Z]{6,20}$/",$word)) { return true; } return false; }
6.对含中文的字符串取子串时,用 mb_substr 进行截取
7.检测中英文混合的字符串长度
";
//结果:22
echo mb_strlen($str,"UTF8")."
"; //结果:12
$strlen = (strlen($str)+mb_strlen($str,"UTF8"))/2;
echo $strlen;
//结果:17
?>
8. 检测是否含有中文
"; //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 "错误输入"; } ?>

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

1. WeChat is a social platform that pays attention to privacy protection. Users cannot see who has visited their Moments or personal homepage. 2. This design is intended to protect user privacy and avoid potential harassment or snooping. 3. Users can only see the likes and comments records in their circle of friends, further ensuring the confidentiality of personal information.

Thanks to netizens Qing Qiechensi, HH_KK, Satomi Ishihara and Wu Yanzu of South China for submitting clues! According to news on September 2, there are recent rumors that "iPhone 16 may not support WeChat." In response to this, a reporter from Shell Finance called Apple's official hotline. Apple's technical consultant in China responded that whether iOS systems or Apple devices can continue to use WeChat, and WeChat The issue of whether it can continue to be listed and downloaded on the Apple App Store requires communication and discussion between Apple and Tencent to determine the future situation. Software App Store and WeChat Problem Description Software App Store technical consultant pointed out that developers may need to pay fees to put software on the Apple Store. After reaching a certain number of downloads, Apple will need to pay corresponding fees for subsequent downloads. Apple is actively communicating with Tencent,

1. To recover deleted WeChat chat history, you need to use two mobile phones for data migration. 2. On the old phone, click [Me] → [Settings] → [Chat] → [Chat History Migration and Backup]. 3. Select [Migrate] and set the target device platform. After selecting the chat history to be restored, click [Start]. 4. Then log in to the same account on the new phone and scan the QR code on the old phone to start the migration. 5. After the migration is completed, the deleted chat history will be restored to the new phone.

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

1. On the old device, click "Me" → "Settings" → "Chat" → "Chat History Migration and Backup" → "Migrate". 2. Select the target platform device to be migrated, select the chat records to be migrated, and click "Start". 3. Log in with the same WeChat account on the new device and scan the QR code to start chat record migration.

Rumors of WeChat supporting iPhone 16 were debunked. Thanks to netizens Xi Chuang Jiu Shi and HH_KK for submitting clues! According to news on September 2, there are rumors today that WeChat may not support iPhone 16. Once the iPhone is upgraded to the iOS 18.2 system, it will not be able to use WeChat. According to "Daily Economic News", it was learned from people familiar with the matter that this rumor is a rumor. Apple's response: According to Shell Finance, Apple's technical consultant in China responded that the issue of whether WeChat can continue to be used on iOS systems or Apple devices, and whether WeChat can continue to be listed and downloaded in the Apple App Store, needs to be resolved between Apple and Tencent. Only through communication and discussion can we determine the future situation. Currently, Apple is actively communicating with Tencent to confirm whether Tencent will continue to

1. Open the WeChat mini program and enter the corresponding mini program page. 2. Find the member-related entrance on the mini program page. Usually the member entrance is in the bottom navigation bar or personal center. 3. Click the membership portal to enter the membership application page. 4. On the membership application page, fill in relevant information, such as mobile phone number, name, etc. After completing the information, submit the application. 5. The mini program will review the membership application. After passing the review, the user can become a member of the WeChat mini program. 6. As a member, users will enjoy more membership rights, such as points, coupons, member-exclusive activities, etc.

1. Avoid frequently publishing advertising content, such as continuous promotion of products or discounts. 2. Use marketing or sensitive words with caution, such as [order], [purchase], etc. 3. Reasonably control the release frequency and avoid frequent updates, at least half an hour apart. 4. Present the copy in paragraphs, with each paragraph not exceeding 100 words, and the length controlled to be within 6 lines and within 200 words. 5. Avoid copying and pasting the same copy, and ensure that the published content is original or appropriately adapted.
