JSON无法返回西里尔数据

时间:2016-04-12 10:59:39

标签: php json mysqli

$connect = mysqli_connect("localhost", "root", "123456", "json_test");

$sql = "SELECT * FROM names";
$query = mysqli_query( $connect,$sql );
while( $row=mysqli_fetch_array($query) ){
    $arr[]=array(
        'id' => $row['id'],
        'title' => $row['name']
    );
}
echo json_encode( $arr );

正在回归???????这是西里尔文(utf-8)。如何解决?

2 个答案:

答案 0 :(得分:1)

尝试添加 $ mysqli-> set_charset(“utf8”)。请检查以下代码并告诉我

$connect = mysqli_connect("localhost", "root", "123456", "json_test");
$connect->set_charset("utf8");

$sql = "SELECT * FROM names";
$query = mysqli_query( $connect,$sql );
while( $row=mysqli_fetch_array($query) ){
    $arr[]=array(
        'id' => $row['id'],
        'title' => $row['name']
    );
}
echo json_encode( $arr );

答案 1 :(得分:1)

mysqli_set_charset()函数指定从数据库服务器发送数据和向数据库服务器发送数据时使用的默认字符集。

您需要在连接后添加mysqli_set_charset($connect,"utf8");

$connect = mysqli_connect("localhost", "root", "123456", "json_test");
mysqli_set_charset($connect,"utf8");

阅读http://php.net/manual/en/mysqli.set-charset.php