| 
       可能用很多朋友使用json数据时利用php自带的函数JSON_DECODE/JSON_ENCODE处理中文内容时会碰到出现NULL或乱码问题,下面我来给大家介绍为什么会出现这样的问题,例: 
	
	- <?php 
 
	- $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 
 
	- var_dump(json_decode($json)); 
 
	- var_dump(json_decode($json, true)); 
 
	- ?> 
 
	 
 
输出结果 
object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}
完全正确没有任何问题,那么我们测试中文,代码如下: 
	
	- <?php 
 
	- $json = '{"a":"中国人人"}'; 
 
	- var_dump(json_decode($json)); 
 
	- ?> 
 
	 
 
结果:{"text":null,"status":1},后来从php手册中得出,json_encode 和 json_decode只支持utf-8编码的字符,GBK的字符要用json就得转换一下,这样我们就好办了 
转换一个编码,代码如下: 
	
	-  
 
	-  
 
	-  
 
	- function ct2($s){ 
 
	-     if(is_numeric($s)) { 
 
	-         return intval($s); 
 
	-     } else { 
 
	-         return iconv("GBK","UTF-8",$s); 
 
	-     } 
 
	- } 
 
	-  
 
	-  
 
	-  
 
	- function icon_to_utf8($s) { 
 
	-   if(is_array($s)) { 
 
	-     foreach($s as $key => $val) { 
 
	-       $s[$key] = icon_to_utf8($val); 
 
	-     } 
 
	-   } else { 
 
	-       $s = ct2($s); 
 
	-   } 
 
	-   return $s; 
 
	- } 
 
	- echo json_encode(icon_to_utf8("厦门")); 
 
	 
 
这样还是有时会有问题,后来找了一种在json_encode之前,把所有数组内所有内容都用urlencode()处理一下,然用json_encode()转换成json字符串,最后再用urldecode()将编码过的中文转回来,写了个函数: 
	
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	- function arrayRecursive(&$array, $function, $apply_to_keys_also = false) 
 
	- { 
 
	-     foreach ($array as $key => $value) { 
 
	-         if (is_array($value)) { 
 
	-             arrayRecursive($array[$key], $function, $apply_to_keys_also); 
 
	-         } else { 
 
	-             $array[$key] = $function($value); 
 
	-         } 
 
	-         if ($apply_to_keys_also && is_string($key)) { 
 
	-             $new_key = $function($key); 
 
	-             if ($new_key != $key) { 
 
	-                 $array[$new_key] = $array[$key]; 
 
	-                 unset($array[$key]); 
 
	-             } 
 
	-         } 
 
	-     } 
 
	- } 
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	-  
 
	- function JSON($array) { 
 
	-     arrayRecursive($array, 'urlencode', true); 
 
	-     $json = json_encode($array); 
 
	-     return urldecode($json); 
 
	- } 
 
	 
 
      
      (责任编辑:admin) |