Chinaunix

标题: php json 中文乱码 [打印本页]

作者: yanpuz    时间: 2011-12-20 09:48
标题: php json 中文乱码
方法一:
  1. <?php
  2. $code = json_encode($str);
  3. $code = preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))", $code);
  4. ?>
方法二: 
  1. <?php
  2. // 将数组转换成Json格式,中文需要进行URL编码处理
  3. function Array2Json($array) {
  4.     arrayRecursive($array, 'urlencode', true);
  5.     $json = json_encode($array);
  6.     $json = urldecode($json);
  7.     // ext需要不带引号的bool类型
  8.     $json = str_replace("\"false\"","false",$json);
  9.     $json = str_replace("\"true\"","true",$json);
  10.     return $json;
  11. }
  12. function arrayRecursive(&$array, $function, $apply_to_keys_also = false)
  13. {
  14.     static $recursive_counter = 0;
  15.     if (++$recursive_counter > 1000) {
  16.         die('possible deep recursion attack');
  17.     }
  18.     foreach ($array as $key => $value) {
  19.         if (is_array($value)) {
  20.             arrayRecursive($array[$key], $function, $apply_to_keys_also);
  21.         } else {
  22.             $array[$key] = $function($value);
  23.         }
  24.         if ($apply_to_keys_also && is_string($key)) {
  25.             $new_key = $function($key);
  26.             if ($new_key != $key) {
  27.                 $array[$new_key] = $array[$key];
  28.                 unset($array[$key]);
  29.             }
  30.         }
  31.     }
  32.     $recursive_counter--;
  33. }
  34. ?>






欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2