AJAX返回中文乱码
取来的json数据中文显示 \u5fd9\u5364\u9e25\u732b\u9225\u5b64\u5f9d
这是什么编码?
服务端用iconv('GBK', 'UTF-8',$out)不管用,直接取也是乱码,数据库写入用的utf-8
大哥hehe
9 years, 11 months ago
Answers
<?php
$a = '\u5fd9\u5364\u9e25\u732b\u9225\u5b64\u5f9d';
echo unicode_decode($a);
function unicode_decode($name)
{
// 转换编码,将Unicode编码转换成可以浏览的utf-8编码
$pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
preg_match_all($pattern, $name, $matches);
if (!empty($matches))
{
$name = '';
for ($j = 0; $j < count($matches[0]); $j++){
$str = $matches[0][$j];
if (strpos($str, '\\u') === 0)
{
$code = base_convert(substr($str, 2, 2), 16, 10);
$code2 = base_convert(substr($str, 4), 16, 10);
$c = chr($code).chr($code2);
$c = iconv('UCS-2', 'UTF-8', $c);
$name .= $c;
}else{
$name .= $str;
}
}
}
return $name;
}
PS: 文件保存编码为
utf-8
.
转换函数取自于: PHP中对汉字进行UNICODE编码和解码的实现
huandi
answered 9 years, 11 months ago