YxzzJ

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

由于将Array转换为json的json_encode()方法仅能将utf-8字符集进行转换,不是utf-8格式的中文字符会变成null,需要对Array中的字符进行统一转码,但是iconv()方法只能转换字符串类型编码,网上找到如下方法可以统一解决string类型和Array类型的转码问题

function auto_charset($fContents, $from='gbk', $to='utf-8') {
$from = strtoupper($from) == 'UTF8' ? 'utf-8' : $from;
$to = strtoupper($to) == 'UTF8' ? 'utf-8' : $to;
if (strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents))) {
return $fContents;
}
if (is_string($fContents)) {
if (function_exists('mb_convert_encoding')) {
return mb_convert_encoding($fContents, $to, $from);
} else if (function_exists('iconv')) {
return iconv($from, $to, $fContents);
} else {
return $fContents;
}
} else if (is_array($fContents)) {
foreach ($fContents as $key => $val) {
$_key = auto_charset($key, $from, $to);
$fContents[$_key] = auto_charset($val, $from, $to);
if ($key != $_key)
unset($fContents[$key]);
}
return $fContents;
}
else {
return $fContents;
}
}

posted on 2016-09-14 10:57  YxzzJ  阅读(247)  评论(0编辑  收藏  举报