JSON解码为UTF-8

时间:2012-03-27 02:59:34

标签: php json

我想将json输出解码为utf-8。

$sql = "select * from nganhang";
$kq = mysql_query($sql);

$posts = array();
while($post = mysql_fetch_assoc($kq)) 
    {
            $posts[] = array('node_list_bank'=>array_map('utf8_encode',$post));
        }

    header('Content-type: application/json');
    echo json_encode(array('list_bank'=>$posts));

此输出

{"list_bank":[{"node_list_bank":{"manganhang":"acb","tennganhang":"Ng\u00c3\u00a2n h\u00c3\u00a0ng \u00c3\u0081 Ch\u00c3\u00a2u ACB"}},{"node_list_bank":{"manganhang":"agb","tennganhang":"Agribank - Ng\u00c3\u00a2n h\u00c3\u00a0ng n\u00c3\u00b4ng nghi\u00e1\u00bb\u0087p v\u00c3\u00a0 ph\u00c3\u00a1t tri\u00e1\u00bb\u0083n n\u00c3\u00b4ng th\u00c3\u00b4n Vi\u00e1\u00bb\u0087t Nam"}},{"node_list_bank":{"manganhang":"mhb","tennganhang":"Ng\u00c3\u00a2n h\u00c3\u00a0ng ph\u00c3\u00a1t tri\u00e1\u00bb\u0083n nh\u00c3\u00a0 \u00c4\u0091\u00e1\u00bb\u0093ng b\u00e1\u00ba\u00b1ng s\u00c3\u00b4ng C\u00e1\u00bb\u00adu Long"}},{"node_list_bank":{"manganhang":"bidv","tennganhang":"Ng\u00c3\u00a2n h\u00c3\u00a0ng \u00c4\u0090\u00e1\u00ba\u00a7u t\u00c6\u00b0 v\u00c3\u00a0 Ph\u00c3\u00a1t tri\u00e1\u00bb\u0083n Vi\u00e1\u00bb\u0087t Nam"}},{"node_list_bank":{"manganhang":"vdb","tennganhang":"Ng\u00c3\u00a2n h\u00c3\u00a0ng Ph\u00c3\u00a1t tri\u00e1\u00bb\u0083n Vi\u00e1\u00bb\u0087t Nam"}},{"node_list_bank":{"manganhang":"vbsp","tennganhang":"Ng\u00c3\u00a2n h\u00c3\u00a0ng Ch\u00c3\u00adnh s\u00c3\u00a1ch X\u00c3\u00a3 h\u00e1\u00bb\u0099i Vi\u00e1\u00bb\u0087t Nam"}}]}

我想要输出结果格式uft-8 ...怎么做:(

$encode = json_encode(array('list_bank'=>$posts));
$decode = json_decode($encode,true);
echo $decode;

抱歉,我使用英语不好:(

2 个答案:

答案 0 :(得分:0)

您可能需要发送正确的标题。

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

$encode = json_encode(array('list_bank'=>$posts));
$decode = json_decode($encode, true);
print_r($decode);

另外,您不能echo数组,必须使用print_r

答案 1 :(得分:0)

在.php文件的开头包含下一个标题

echo json_encode(array('list_bank'=>$posts), JSON_UNESCAPED_UNICODE);

并在json_encode中添加'JSON_UNESCAPED_UNICODE'

[{message,[{id,"500"}],
    [{from_user,"admin@domain"}],
    [{to_user,"test@domain"}],
    [{txt,"Text message from admin to user"}],
    [{created_at,"2015-08-28 17:48:41"}]},
    ...
 {message,[{id,"550"}],
    [{from_user,"test@domain"}],
    [{to_user,"admin@domain"}],
    [{txt,"message from test to admin"}],
    [{created_at,"2015-08-28 17:48:42"}]}]

请务必删除不需要的utf8_encode()和json_decode()。