gbk和utf8的json转化
2021-05-11 12:27
标签:style dep val return one turn controls stat def gbk和utf8的json转化 标签:style dep val return one turn controls stat def 原文地址:https://www.cnblogs.com/two-bees/p/12055758.html /**
* 将gbk编码转为utf8再json化
* @param $value
* @param int $options
* @return false|string
*/
static function tb_json_encode($value, $options = 0)
{
return json_encode(self::tb_json_convert_encoding($value, ‘GBK‘, ‘UTF - 8‘));
}
/**
* 反json化后,再将utf8编码转为gbk
* @param $str
* @param bool $assoc
* @param int $depth
* @return false|string
*/
static function tb_json_decode($str, $assoc = false, $depth = 512)
{
return self::tb_json_convert_encoding(json_decode($str, $assoc), ‘UTF-8‘, ‘GBK‘);
}
static function tb_json_convert_encoding($m, $from, $to)
{
switch (gettype($m)) {
case ‘integer‘:
case ‘boolean‘:
case ‘float‘:
case ‘double‘:
case ‘NULL‘:
return $m;
case ‘string‘:
return iconv(‘gbk‘, ‘utf-8‘, $m);;
case ‘object‘:
$vars = array_keys(get_object_vars($m));
foreach ($vars as $key) {
$m->$key = self::tb_json_convert_encoding($m->$key, $from, $to);
}
return $m;
case ‘array‘:
foreach ($m as $k => $v) {
$m[self::tb_json_convert_encoding($k, $from, $to)] = self::tb_json_convert_encoding($v, $from, $to);
}
return $m;
default:
}
return $m;
}