doujie7346 2014-07-10 07:14
浏览 451
已采纳

将数组转换为JSON时,json_encode返回JSON_ERROR_UTF8 [关闭]

I'm trying to convert an array with values in brazilian portuguese to JSON.

Here is an array example:

array(1) {
  ["title"]=>
  string(77) "Cartão Credicard Universitário Visa Crédito "
}

If I use mb_detect_encoding it shows that all values and keys are either in ASCII or UTF8.

However if I try to use json_encodein order to generate the json, it returns a false and json_last_error function says that the error is JSON_ERROR_UTF8

But if I apply first the utf8_encode_deep function to the array ( http://php.net/manual/es/function.utf8-encode.php ), the json is generated without giving any errors.

The problem with this solution is that it returns certain words with bad codification.

Example:

Word before applying utf8_encode: Cartão (good codification)

Word after applying utf8_encode: Cartão (bad codification)

So although it generates the JSON, it doesn't solve my problem because it messes up the words.

Here is the code I'm using:

try {
  $dbh = new PDO("mysql:host=$hostname;dbname=$database;", $username, $password);
  $sql = "SELECT title FROM card";
  $stmt = $dbh->query($sql);

  $result = $stmt->fetch(PDO::FETCH_ASSOC);
  $json = $json_encode($result);
  $error = json_last_error();

  var_dump($json, $error === JSON_ERROR_UTF8);
} catch (PDOException $e) {
        echo 'Connection failed: ' . $e->getMessage() . '
';
}

If I try to connect to the database using charset=utf8 or charset=utf8mb4, it retrieves Cartão(bad codification), instead of Cartão (good codification)

I have also tried to use JSON_UNESCAPED_UNICODE as parameter of json_encode, but the result remains the same as without using this parameter.

Any suggestions?

UPDATE: I've simplified the example with one concrete case where this problem is happening.

UPDATE 2: Added some code in order to clarify the example, also added some explanations about possible solutions in the comments.

  • 写回答

1条回答 默认 最新

  • donqo88682 2014-07-10 08:38
    关注

    "If I try to connect to the database using charset=utf8 or charset=utf8mb4, it retrieves Cartão(bad codification), instead of Cartão (good codification)"

    You are using latin1 as the display encoding, so that UTF-8 encoded, correct, text is displayed incorrectly.

    Add charset=utf8 to the connection string and also set the response charset to UTF-8:

    header('Content-Type: text/html;charset=utf-8');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码