You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nginx服务器PHP脚本返回空HTTP响应问题求助

问题描述

我有一个运行在Nginx服务器上的Web应用,服务器端采用PHP开发,前端使用AngularJS。通过HTTP POST请求向backend/get_questions.php发送team_id、user_id、user_type三个参数,以获取数据库中的数据,前端代码如下:

$http.post("backend/get_questions.php", { team_id: $scope.user.team_id, user_id: $scope.user.user_id, user_type: $scope.user.user_type })
       .then(function(response){
            console.log(response);
            if(response.data.success){
               $scope.questions = response.data.questions.slice();
            } else {
               alert(response.data.message);
            }
})

在get_questions.php脚本中,我通过PDO连接数据库,并从questions表中获取数据后返回给客户端,核心代码如下:

$questions = $statement->fetchAll(PDO::FETCH_ASSOC);

if(count($questions) > 0){
    $response = array("success" => true, "message" => "Data successfully retrieved", "questions" => $questions);
} else {
    $response = array("success" => false, "message" => "There are no records related to the specified team.");
}

echo json_encode($response);

其他HTTP请求均正常,但该请求返回的响应data属性为空字符串:

{
  "data": "",
  "status": 200,
  "config": {
    "method": "POST",
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "jsonpCallbackParam": "callback",
    "Content-Type": "application/json",
    "url": "backend/get_questions.php",
    "data": {
      "team_id": 4,
      "user_id": "professor@professor.com",
      "user_type": "professor"
    },
    "headers": {
      "Accept": "application/json, text/plain, */*",
      "Content-Type": "application/json;charset=utf-8"
    }
  },
  "statusText": "OK",
  "xhrStatus": "complete"
}

尝试移除关联数组中的questions键后,响应恢复正常。通过json_last_error_msg()排查得到错误信息:

Malformed UTF-8 characters, possibly incorrectly encoded

请问可能的原因是什么?


问题原因分析
  • 数据库与PHP编码不匹配:questions表中存储的数据可能使用了非UTF-8编码(如GBK、Latin1),而json_encode默认要求输入为UTF-8编码。当数据中包含这类非UTF-8的特殊字符时,序列化会失败,返回空字符串。其他请求无问题,是因为对应的数据中没有这类非法字符。

  • PDO连接未指定UTF-8字符集:如果PDO连接数据库时未设置UTF-8字符集(比如连接字符串中未添加charset=utf8mb4参数),即使数据库本身是UTF-8编码,查询返回的数据也可能出现编码混乱,导致json_encode无法处理。

  • 数据存在无效UTF-8字节序列:questions表的部分字段(如问题内容、描述)可能包含了无效的UTF-8字符,比如截断的多字节字符、特殊控制字符,这些字符会破坏整个数组的序列化流程,导致json_encode返回空。

  • PHP配置或版本限制:部分旧版PHP对某些UTF-8字符的处理存在bug;若未开启JSON_PARTIAL_OUTPUT_ON_ERROR配置项,当遇到编码错误时,json_encode会直接返回空字符串,而非输出可正常序列化的部分内容。


内容的提问来源于stack exchange,提问作者ErCabesa22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 03:35:17