遇到个很幼稚的问题,用json_encode把数组转换为json时,发现转化的值为null。怎么回事呢?查找手册:发现了下面的话:
该函数只能接受 UTF-8 编码的数据(译注:指字符/字符串类型的数据)
原来数组中有中文,需要转码哦,写个转换字符编码的函数吧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | function encodeConvert($str,$fromCode,$toCode) { if (strtoupper($toCode) == strtoupper($fromCode)) return $str; if (is_string($str)) { if (function_exists('mb_convert_encoding')) { return mb_convert_encoding($str, $toCode, $fromCode); } else { return iconv($fromCode, $toCode, $str); } } elseif (is_array($str)) { foreach ($str as $k => $v) { $str[$k] = encodeConvert($v, $fromCode, $toCode); } return $str; } return $str; } |
对于数组,通过下面方式json_encode调用,一切ok。
1 2 | $json_api=json_encode(encodeConvert($json_api,'gb2312','utf-8')); $json_api=json_decode(json_decode($json_api)); |