鍍金池/ 問答/Java  PHP  HTML/ json字符串,中文Unicode編碼,PHP解析問題,謝謝!

json字符串,中文Unicode編碼,PHP解析問題,謝謝!

http://ip.taobao.com/instruct...

接口返回這樣的數(shù)據(jù),

{"code":0,"data":{"ip":"210.75.225.254","country":"\u4e2d\u56fd","area":"\u534e\u5317",
"region":"\u5317\u4eac\u5e02","city":"\u5317\u4eac\u5e02","county":"","isp":"\u7535\u4fe1",
"country_id":"86","area_id":"100000","region_id":"110000","city_id":"110000",
"county_id":"-1","isp_id":"100017"}}

類似這樣的

"region":"\u5317\u4eac\u5e02","city":"\u5317\u4eac\u5e02"

php怎么解析出來正確的漢字呢?
謝謝!

回答
編輯回答
乞許

json_decode($json,true);

2017年8月7日 06:53
編輯回答
萌吟

解決辦法:
首先自定義一個函數(shù),處理接到接口的數(shù)據(jù),將所有Unicode編碼的替換為utf8,

function decodeUnicode($str)
    {
        return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
            create_function(
                '$matches',
                'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
            ),
            $str);
    }

PHP接口獲取數(shù)據(jù)后,先執(zhí)行這個函數(shù),替換后,再執(zhí)行 json_decode($str, true),這樣直接可以把接口數(shù)據(jù)轉(zhuǎn)化為數(shù)組了

2017年11月4日 20:58
編輯回答
卟乖
function unicodeDecode($str){
  $json = '{"str":"'.$str.'"}';
  $arr = json_decode($json,true);
  if(empty($arr)) return ''; 
  return $arr['str'];
}
2018年5月16日 12:16
編輯回答
毀與悔
var_dump(json_decode('{"code":0,"data":{"ip":"210.75.225.254","country":"\u4e2d\u56fd","area":"\u534e\u5317",
"region":"\u5317\u4eac\u5e02","city":"\u5317\u4eac\u5e02","county":"","isp":"\u7535\u4fe1",
"country_id":"86","area_id":"100000","region_id":"110000","city_id":"110000",
"county_id":"-1","isp_id":"100017"}}'));
2018年1月12日 14:01