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 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真