PHP json_encode json_decode UTF-8

时间:2010-11-02 10:59:47

标签: php utf-8 json

如何将带有国际字符的json编码字符串保存到数据库中,然后在浏览器中解析编码后的字符串?

<?php           
    $string = "très agréable";  
    // to the database 
    $j_encoded = json_encode(utf8_encode($string)); 
    // get from Database 
    $j_decoded = json_decode($j_encoded); 
?>    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr">
    <?= $j_decoded ?>
</html> 

10 个答案:

答案 0 :(得分:35)

json utf8编码和解码:

json_encode($data, JSON_UNESCAPED_UNICODE)

json_decode($json, false, 512, JSON_UNESCAPED_UNICODE)

强制utf8也可能有帮助:http://pastebin.com/2XKqYU49

答案 1 :(得分:28)

  header('Content-Type: application/json; charset=utf-8');

答案 2 :(得分:23)

这是编码问题。看起来在某些时候,数据表示为ISO-8859-1。

您的流程的每个部分都需要采用UTF-8编码。

  • 数据库连接

  • 数据库表

  • 您的PHP文件(如果您在该文件中使用特殊字符,如上例所示)

  • 您输出的content-type标题

答案 3 :(得分:11)

如果源文件已经是utf8,则删除utf8_ *函数。 php5将字符串存储为byte数组。

你应该在html中添加一个用于编码的元标记,你应该添加一个http标头,它将传输编码设置为utf-8。

<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

并在php中

<?php
header('Content-Type: text/html; charset=utf-8');

答案 4 :(得分:4)

尝试发送UTF-8字符集标题:

<?php header ('Content-type: text/html; charset=utf-8'); ?>

HTML meta:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

答案 5 :(得分:3)

  1. utf8_decode $j_decoded = utf8_decode(json_decode($j_encoded)); 编辑 或者更正确$j_encoded = json_encode($j_encoded); $j_decoded = json_decode($j_encoded);不需要en / decoding utf8
  2. <meta charset="utf-8" />

答案 6 :(得分:0)

如果你得到&#34;意外的角色&#34;错误你应该检查是否有BOM(字节顺序标记保存到你的utf-8 json。 您可以删除第一个字符,也可以在没有BOM的情况下保存。

答案 7 :(得分:0)

为我工作:)

function jsonEncodeArray( $array ){
    array_walk_recursive( $array, function(&$item) { 
       $item = utf8_encode( $item ); 
    });
    return json_encode( $array );
}

答案 8 :(得分:0)

对我来说这两种方法

<?php

header('Content-Type: text/html; charset=utf-8');

echo json_encode($YourData, \JSON_UNESCAPED_UNICODE);

答案 9 :(得分:0)

我有同样的问题。可能会有所不同,具体取决于您如何将数据放入数据库,但是请尝试对我有用的方法:

$str = json_encode($data);
$str = addslashes($str);

在将数据保存到数据库之前执行此操作。