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 –
你是那麼對!非常感謝,我看了一下手冊,並沒有意識到這一點。如果您想正式回答這些問題,我可以對其進行投票並標記出來。再次感謝! –
完成,謝謝 –