Skip to content

Instantly share code, notes, and snippets.

@zhouyl
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save zhouyl/a6edb3976c58d0aa3057 to your computer and use it in GitHub Desktop.

Select an option

Save zhouyl/a6edb3976c58d0aa3057 to your computer and use it in GitHub Desktop.
字符编码自动转换
<?php
/**
* 支持对多维数组,对象,... 进行编码转换
* 在不指定来源编码时,由系统自动检测编码类型
*
* @link http://cn2.php.net/manual/zh/function.mb-detect-encoding.php
* @link http://cn2.php.net/manual/zh/function.mb-detect-order.php
* @param mixed $data 需要转换的数据
* @param string $to_encoding 目标编码类型
* @param string $from_encoding 来源编码类型,默认自动检测类型
* @param mixed $encoding_list 编码检测类型及顺序
* @return mixed
*/
function to_encoding($data, $to_encoding, $from_encoding = null,
$encoding_list = 'UTF-8,GBK,CP936,ISO-8859-1,ASCII')
{
if (is_string($data)) {
if ($from_encoding === null) {
$from_encoding = mb_detect_encoding($data, $encoding_list);
}
if (strtoupper($to_encoding) !== strtoupper($from_encoding)) {
$data = mb_convert_encoding($data, $to_encoding, $from_encoding);
}
} elseif (is_array($data) || is_object($data)) {
foreach ($data as $key => & $val) {
$val = call_user_func_array(__FUNCTION__, array($val, $to_encoding, $from_encoding));
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment