doufei5315 2017-02-12 21:35
浏览 116
已采纳

PHP在JSON数组中传回一个带有特殊字符的对象

All, I have a php file which runs a MYSQL query and places the result in an array. The table has several fields, one has the characters '-' and '%' as part of a varchar string. When I pass this back in a JSON array it simply dies. Here are the code sections..

PHP file

// fetch merit guidelines
$meritGuideline = array();
$sql = "SELECT smg.id, year, ea.rating, ratioUpper, ratioLower, guideline, guidelineNum FROM spot_merit_guide smg JOIN epm_annual ea ON ea.id = smg.rating WHERE year = '$spotYear'";
$query = mysqli_query($con, $sql);
while ($row = mysqli_fetch_assoc($query)) {
    $meritGuideline[] = $row;
}
mysqli_free_result($query);

Then I return it with this

echo json_encode(array('meritGuideline' => $meritGuideline));

The mysql table field guideline contains the string 0 - 4%.

  • 写回答

1条回答 默认 最新

  • douji9816 2017-02-13 00:14
    关注

    First, try encoding the data to UTF-8:

    // fetch merit guidelines
    $meritGuideline = array();
    $sql = "SELECT smg.id, year, ea.rating, ratioUpper, ratioLower, guideline, guidelineNum FROM spot_merit_guide smg JOIN epm_annual ea ON ea.id = smg.rating WHERE year = '$spotYear'";
    $query = mysqli_query($con, $sql);
    while ($row = mysqli_fetch_assoc($query)) {
        $meritGuideline[] = utf8_encode($row); // ENCODE TO UTF-8
    }
    mysqli_free_result($query);
    

    Then run this for debug purposes:

    echo json_encode(array('meritGuideline' => $meritGuideline));
    echo 'Error: ' . json_last_error_msg();
    
    1. If the first line above does output your JSON, then the problem was most likely a hidden UTF-8 only special/invisible space character, which are often mischievous when dealing with JSON encoding or even Javascript code parsing in the browser. Here are some examples of these "special" space characters:

      No-break space: http://www.fileformat.info/info/unicode/char/00a0/index.htm

      Zero-width space: http://www.fileformat.info/info/unicode/char/200b/index.htm

    2. If the first line still doesn't output anything, then the second line will allow you to see the exact error that's happening inside PHP's JSON encoder.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器