search
HomeBackend DevelopmentPHP TutorialPHP对了,可是对接到微信只返回array

$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;



在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;}

你的表字段是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;}


都改了,还是不行,烦死了,用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
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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),