This question already has answers here:
UTF-8 all the way through

(16个答案)


6年前关闭。




我在执行json_encode()时遇到阿拉伯字符问题,它总是返回????,在数据库中所有字段和数据库都是utf8

我的代码:
$query   = mysql_query("SELECT * FROM `Names`");

if (!$query) {
$message  = 'Invalid query: ' . mysql_error() . "\n";
die($message);
}else
{
    while ($row = mysql_fetch_assoc($query))
    {
     $result[] = array(
        'Mid' => $row['Mid'],
        'Uid' => $row['Uid'],
        'Cid' => $row['Cid'],
        'Name' => $row['Name'],
        'city' => $row['city'],
        'status' => $row['status'],
        'Mobile' => $row['Mobile'],
        'Phone' => $row['Phone'],
        'Email' => $row['Email']);
    }
      header('Content-Type: application/json; charset=utf-8');
      echo json_encode($result);
}

结果看起来像:
[{"Mid":"17","Uid":"1","Cid":"8","Name":"???? ?? ??????? ?? ???","city":"?????",

请帮我

最佳答案

在发送查询之前尝试一下

mysql_query("SET NAMES 'utf8'");

或这个(如果您的PHP版本是5.4.0或更高版本)
json_encode($result, JSON_UNESCAPED_UNICODE);

注意:如果您的数据以十六进制格式存储,请用json_encode括住mysql_escape_string()

08-19 01:00