Last active
August 29, 2015 14:03
-
-
Save zhouyl/a6edb3976c58d0aa3057 to your computer and use it in GitHub Desktop.
字符编码自动转换
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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