PHP:JSON字符串转换为中文,中文转换为JSON字符串
/** * 中文转换为JSON字符串 * @param $chinese_str 中文:可以包含中文字母数字 * @return string */ function json_encode($chinese_str) { $chinese_str = iconv('UTF-8', 'UCS-2', $chinese_str); $len = strlen($chinese_str) - 1; $str = ''; for ($i = 0; $i < $len; $i = $i + 2) { $c1 = $chinese_str[$i]; $c2 = $chinese_str[$i + 1]; $unicode1=ord($c1); $unicode2=ord($c2); if ($unicode1) { // 两个字节的文字 $unicode1='\u'.base_convert($unicode1, 10, 16); $unicode2=base_convert($unicode2, 10, 16); if(in_array($unicode2,array('a','b','c','d','e','f'))){ $unicode2='0'.$unicode2; } $str.=$unicode1.$unicode2; }else{ $str.=$c2; } } return $str; } /** * JSON字符串转换为中文 * @param $json_str JSON字符串 * @return string */ function json_decode($json_str) { // 转换编码,将JSON字符串转换成可以浏览的utf-8编码 $pattern = '/([\w]+)|(\\\u([\w]{4}))/i'; preg_match_all($pattern, $json_str, $matches); $chinese_str = ''; if (!empty($matches)) { $count=count($matches[0]); for ($j = 0; $j < $count; $j++) { $str = $matches[0][$j]; if (strpos($str, '\\u') === 0) { $code = base_convert(substr($str, 2, 2), 16, 10); $code2 = base_convert(substr($str, 4), 16, 10); $c = chr($code).chr($code2); $c = iconv('UCS-2', 'UTF-8', $c); $chinese_str .= $c; } else { $chinese_str .= $str; } } } return $chinese_str; }
突然十年便过去,都什么时候了,努力,奋斗!