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);
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失