unicode编码转汉字

时间:2022-02-07 20:24:24

问题:
使用json_encode方法,中文未做处理,转变成Unicode编码,中文字符显示串乱码
解决示例:

  1. 已存储为json格式字符串,正则替换
ini_set("max_execution_time", -1);//php脚本执行时间限制处理
$arr = array(42, 66, 69, 71);
$strs = Adlog::where('type', 1)->select('id','msg_str')->get();
$sql = "update ad_log set msg_str = case id ";
$ids = array();
foreach ($strs as $k => $v){
$ids[] =$v->id;
if(in_array($v->id,$arr)){//中文字符串显示为类似u65b0u6d6au5faeu535a 情况
$v->msg_str = preg_replace("#u([0-9a-f]{4})#ie","iconv('UCS-2','UTF-8', pack('H4', '\\1'))", $v->msg_str);
$msg = preg_replace("#u([0-9a-f]{4})#ie","iconv('UCS-2','UTF-8', pack('H4', '\\1'))", $v->msg_str);
}else{//字符串正常显示情况\u65b0\u6d6a\u5fae\u535a
$v->msg_str = preg_replace("#\\\u([0-9a-f]{4})#ie","iconv('UCS-2','UTF-8', pack('H4', '\\1'))", $v->msg_str);
$msg = preg_replace("#\\\u([0-9a-f]{4})#ie","iconv('UCS-2','UTF-8', pack('H4', '\\1'))", $v->msg_str);
}
$sql .= 'when '.$v->id.' then \''.$msg.'\' ';
}
header('content-type:text/html;charset=utf-8');
//dd($strs->toArray());die;
//sql语句输出
$sql .= 'end where id in ('.implode(',', $ids).')';
//echo $sql;die;
$r = DB::update($sql);
echo $r;die;
  1. 未存储时,处理
    先将字符串urlencode,在json_encode,在urldecode
    解决示例:
$aInfo = array(
'hospital' => urlencode(Hospitaluser::find($iHospitalid)->hospital),
'hospital_id' => $iHospitalid,
);
$aInfo = urldecode(json_encode($aInfo));//中文Unicode转义处理

针对数组处理方式–借鉴~

function encode_json($str) {  
return urldecode(json_encode(url_encode($str)));
}
function url_encode($str) {
if(is_array($str)) {
foreach($str as $key=>$value) {
$str[urlencode($key)] = url_encode($value);
}
} else {
$str = urlencode($str);
}

return $str;
}