1
我有一个接收XML结构的字符串。 其中一个元素包含汉字。 为了将XML转换为json,我使用了json_encode()。汉字输出乱码。使用json_encode将XML从XML转换为json会扰乱字符串的编码
我试着用mb_detect_encoding检查编码,甚至试过列出的解决方案here。
我搜索了很多(很多),发现了很多其他的资源,但他们都没有解决我的问题。任何帮助深表感谢。
代码:
<?php
$str = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<rootjson>
<widget>
<debug>on</debug>
<text>
<data>點擊這裡</data>
<size>36</size>
<alignment>center</alignment>
</text>
</widget>
</rootjson>
XML;
$xml = simplexml_load_string($str);
if ($encoding = mb_detect_encoding($xml, 'UTF-8', true)) echo 'XML is utf8'; //It finds it to be utf8
$json = json_encode($xml, JSON_PRETTY_PRINT);
if ($encoding = mb_detect_encoding($json, 'UTF-8', true)) echo 'Json is utf8'; //It also finds it to be utf8
var_dump($json);
?>
输出:
{
"widget": {
"debug": "on",
"text": {
"data": "\u9ede\u64ca\u9019\u88e1",
"size": "36",
"alignment": "center"
}
}
}
我不觉得,因为它是在告诉这两个$ XML和JSON $是UTF-8编码在这里我可以信任mb_detect_encoding。中国的串点击这里现在显示为
\ u9ede \ u64ca \ u9019 \ u88e1
。
文档阅读文档:http://php.net/manual/en/function.json-encode.php。你需要的是JSON_UNESCAPED_UNICODE –
你是那么对!非常感谢,我看了一下手册,并没有意识到这一点。如果您想正式回答这些问题,我可以对其进行投票并标记出来。再次感谢! –
完成,谢谢 –