dongshi3605 2016-01-30 13:26
浏览 562

Charset Utf8无法使用json编码

I have a php file to return json but the result given not correctly.

Ex: Lập Trình Ứng Dụng in database => L?p Trình ?ng D?ng in view

Here it's php file

  <?php 
    $mysql = new mysqli('localhost','root','','freelancer');
    $result = $mysql->query("select * from tag");
    $rows = array();
    while($row = $result->fetch_array(MYSQL_ASSOC)) {
        $rows[] = array_map("utf8_encode", $row);
    }
    echo json_encode($rows);
    ?>

Hope everyone can help me with this.Thanks for read

  • 写回答

1条回答 默认 最新

  • dqdpz60048 2016-01-30 15:38
    关注

    utf8_encode() only works for strings that are iso-8895-1 encoded. As your string contains non-latin characters, your data can't be encoded in iso-8895-1, so utf8_encode() certainly won't work.

    Instead, you need to ask MySQL to return its data encoded in UTF-8 already by adding set_charset("utf8") to your connection configuration. Now you have UTF-8 encoded strings, you no longer need to re-encode it.

    Your new code should look like:

    <?php 
        $mysql = new mysqli('localhost','root','','freelancer');
        $mysql->set_charset("utf8")
    
        $result = $mysql->query("select * from tag");
        $rows = array();
        while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $rows[] = $row;
        }
        echo json_encode($rows);
    ?>
    
    评论

报告相同问题?

悬赏问题

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