Table of Contents
回复讨论(解决方案)
Home Backend Development PHP Tutorial PHP对了,可是对接到微信只返回array

PHP对了,可是对接到微信只返回array

Jun 20, 2016 pm 12:44 PM

$result = mysql_query($sql, $link); // 执行查询语句
 
$res=array();
while($row = mysql_fetch_array($result)){
    if(条件){
        $res[] = $row["title"].$row["answer"];
    }
}
return $res;
?>
用这个之后PHP是对,可是接到微信就变成单独的回复一个array


回复讨论(解决方案)

把数据连接成串,或编码成 json

return json_encode($res);

return json_encode($res);



这个个也不行啊,回复的是乱码

有人会吗,大师吗

在echo json_encode之前,加上:header('Content-type:application/json;charset=utf-8');

在echo json_encode之前,加上:header('Content-type:application/json;charset=utf-8');


 $sql = "select  * FROM `record` WHERE title like '%$keyword%'";
    $result = mysql_query($sql, $link); // 执行查询语句

            
     $res=array();
   
             while($row = mysql_fetch_array($result))
                      {
                 
                       
                  
                  $res[]=$row["title"];
                 
            
                      }
                header('Content-type:application/json;charset=utf-8');
                return json_encode($res);
               mysql_close($link);        
}                                  这次返回的值是[]

在echo json_encode之前,加上:header('Content-type:application/json;charset=utf-8');


会不会是这个有错误?


%s


0


在echo json_encode之前,加上:header('Content-type:application/json;charset=utf-8');


 $sql = "select  * FROM `record` WHERE title like '%$keyword%'";
    $result = mysql_query($sql, $link); // 执行查询语句

            
     $res=array();
   
             while($row = mysql_fetch_array($result))
                      {
                 
                       
                  
                  $res[]=$row["title"];
                 
            
                      }
                header('Content-type:application/json;charset=utf-8');
                return json_encode($res);
               mysql_close($link);        
}                                  这次返回的值是[]
返回值为空?那么直接return "hello world";是什么结果?


在echo json_encode之前,加上:header('Content-type:application/json;charset=utf-8');


会不会是这个有错误?


%s


0


你把0去掉试试。
另外:要返回信息,不应该用return,而是echo
    public function responseMsg(){               //get post data, May be due to the different environments        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; //接收微信发来的XML数据        //extract post data        if(!empty($postStr)){                            //解析post来的XML为一个对象$postObj            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);                    $fromUsername = $postObj->FromUserName; //请求消息的用户            $toUsername = $postObj->ToUserName; //"我"的公众号id            $keyword = trim($postObj->Content); //用户发送的消息内容            $time = time(); //时间戳            $msgtype = 'text'; //消息类型:文本            $textTpl = "<xml>                        <ToUserName><![CDATA[%s]]></ToUserName>                        <FromUserName><![CDATA[%s]]></FromUserName>                        <CreateTime>%s</CreateTime>                        <MsgType><![CDATA[%s]]></MsgType>                        <Content><![CDATA[%s]]></Content>                        </xml>";                $contentStr = "输入-h查看帮助吧(=・ω・=)";                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $contentStr);                echo $resultStr;
Copy after login



在echo json_encode之前,加上:header('Content-type:application/json;charset=utf-8');


$sql = "select * FROM `record` WHERE title like '%$keyword%'";
$result = mysql_query($sql, $link); // 执行查询语句


$res=array();

while($row = mysql_fetch_array($result))
{



$res[]=$row["title"];


}
header('Content-type:application/json;charset=utf-8');
return json_encode($res);
mysql_close($link);
} 这次返回的值是[]


返回值为空?那么直接return "hello world";是什么结果?


抱歉哈,刚才评论错了,
完整的是这个样子的,我压根不知道哪错了

/**
* wechat php test
*/

//define your token
function chaxun($keyword){
$dbname = 'app_yqweixiaoxi';
//$host = getenv('HTTP_BAE_ENV_ADDR_SQL_IP');
//$port = getenv('HTTP_BAE_ENV_ADDR_SQL_PORT');
//$user = getenv('HTTP_BAE_ENV_AK');
//$pwd = getenv('HTTP_BAE_ENV_SK');
/*接着调用mysql_connect()连接服务器*/
$link = mysql_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
if(!$link) {
die("Connect Server Failed: " . mysql_error($link));
}
/*连接成功后立即调用mysql_select_db()选中需要连接的数据库*/
if(!mysql_select_db($dbname,$link))
{
die("Select Database Failed: " . mysql_error($link));
}

mysql_query("set names GBK",$link);

$sql = "select * FROM `record` WHERE title like '%$keyword%'";
$result = mysql_query($sql, $link); // 执行查询语句
$res=array();
while($row = mysql_fetch_array($result))
{
$res[]=$row["title"];
}
header('Content-type:application/json;charset=utf-8');
return json_encode($res);
mysql_close($link);
}
define("TOKEN", "YQweixiaoxi");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->responseMsg();


class wechatCallbackapiTest
{
public function valid()
{
$echoStr = $_GET["echostr"];

//valid signature , option
if($this->checkSignature()){
echo $echoStr;
exit;
}
}

public function responseMsg()
{
//get post data, May be due to the different environments
$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

//extract post data
if (!empty($postStr)){

$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = $postObj->FromUserName;
$toUsername = $postObj->ToUserName;
$keyword = trim($postObj->Content);
$time = time();
$textTpl = "


%s



";
if(!empty($keyword ))


{
$msgType = "text";

$contentStr= chaxun($keyword);

$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
echo $resultStr;

}else{
echo "Input something...";
}

}else {
echo "";
exit;
}
}

private function checkSignature()
{
$signature = $_GET["signature"];
$timestamp = $_GET["timestamp"];
$nonce = $_GET["nonce"];

$token = TOKEN;
$tmpArr = array($token, $timestamp, $nonce);
sort($tmpArr);
$tmpStr = implode( $tmpArr );
$tmpStr = sha1( $tmpStr );

if( $tmpStr == $signature ){
return true;
}else{
return false;
}
}
}

?>



在echo json_encode之前,加上:header('Content-type:application/json;charset=utf-8');


$sql = "select * FROM `record` WHERE title like '%$keyword%'";
$result = mysql_query($sql, $link); // 执行查询语句


$res=array();

while($row = mysql_fetch_array($result))
{



$res[]=$row["title"];


}
header('Content-type:application/json;charset=utf-8');
return json_encode($res);
mysql_close($link);
} 这次返回的值是[]


返回值为空?那么直接return "hello world";是什么结果?





在echo json_encode之前,加上:header('Content-type:application/json;charset=utf-8');


$sql = "select * FROM `record` WHERE title like '%$keyword%'";
$result = mysql_query($sql, $link); // 执行查询语句


$res=array();

while($row = mysql_fetch_array($result))
{



$res[]=$row["title"];


}
header('Content-type:application/json;charset=utf-8');
return json_encode($res);
mysql_close($link);
} 这次返回的值是[]


返回值为空?那么直接return "hello world";是什么结果?


数据库的是这样的

你的表字段是UTF-8,所以应该 mysql_query("set names utf8",$link);

另外,有个地方稍微改下(改不改都行,不过echo的数据都应该是XML格式的):

if(!empty($keyword )){	$msgType = "text";        	$contentStr = chaxun($keyword);	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);    echo $resultStr;}else{	$msgType = "text";  	$contentStr = "input something...";    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);    echo $resultStr;}
Copy after login
Copy after login

你的表字段是UTF-8,所以应该 mysql_query("set names utf8",$link);

另外,有个地方稍微改下(改不改都行,不过echo的数据都应该是XML格式的):

if(!empty($keyword )){	$msgType = "text";        	$contentStr = chaxun($keyword);	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);    echo $resultStr;}else{	$msgType = "text";  	$contentStr = "input something...";    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);    echo $resultStr;}
Copy after login
Copy after login

都改了,还是不行,烦死了,用return返回array,用echo 回复公众号暂停服务

1、你是在做微信应用,而微信都是 utf-8 编码的
所以你 mysql_query("set names GBK",$link); 是不对的
要 mysql_query("set names utf8",$link);
2、你把传入的 utf-8 数据 $keyword 当做 gbk 解释
这就造成了 chaxun 函数返回空数组
当然确实不存在的时候,也是返回空数组的
3、由
$contentStr= chaxun($keyword); 
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
可知,$contentStr 应是一个字符串,而 chaxun 返回的是数组,所以可能需要
$contentStr = json_encode(chaxun($keyword));

$contentStr = join(',', chaxun($keyword));

1、用echo 回复公众号暂停服务====》可能是代码有语法错误或者error,在你的域名里运行这个脚本看看有没有报错。
2、试一下,不进行查找数据库,直接让$contentStr = "字符串";然后echo $resultStr;  看看是不是数据取出问题

1、用echo 回复公众号暂停服务====》可能是代码有语法错误或者error,在你的域名里运行这个脚本看看有没有报错。
2、试一下,不进行查找数据库,直接让$contentStr = "字符串";然后echo $resultStr;  看看是不是数据取出问题


问题解决了,谢谢你,大师傅

1、你是在做微信应用,而微信都是 utf-8 编码的
所以你 mysql_query("set names GBK",$link); 是不对的
要 mysql_query("set names utf8",$link);
2、你把传入的 utf-8 数据 $keyword 当做 gbk 解释
这就造成了 chaxun 函数返回空数组
当然确实不存在的时候,也是返回空数组的
3、由
$contentStr= chaxun($keyword); 
$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
可知,$contentStr 应是一个字符串,而 chaxun 返回的是数组,所以可能需要
$contentStr = json_encode(chaxun($keyword));

$contentStr = join(',', chaxun($keyword));


大师啊,大师啊,解决了,佩服啊 
太感谢了
Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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.

See all articles