码迷,mamicode.com
首页 > 编程语言 > 详细

php实现转码的方式(支持数组类型转码)

时间:2016-09-14 12:33:51      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:

由于将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;
}
}

php实现转码的方式(支持数组类型转码)

标签:

原文地址:http://www.cnblogs.com/yxzzj/p/5871074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!