好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

PHP JSON_DECODE/JSON_ENCODE中文内容为NULL或乱码 - php函

PHP JSON_DECODE/JSON_ENCODE中文内容为NULL或乱码

可能用很多朋友使用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就得转换一下,这样我们就好办了

转换一个编码,代码如下:

/*       字符串GBK转码为UTF-8,数字转换为数字。   */   function  ct2( $s ){       if ( is_numeric ( $s )) {           return   intval ( $s );      }  else  {           return  iconv( "GBK" , "UTF-8" , $s );      }  }  /*       批量处理gbk->utf-8   */   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对数组中所有元素做处理   *    @param    string    &$array        要处理的字符串   *    @param    string    $function    要执行的函数   *    @return boolean    $apply_to_keys_also        是否也应用到key上   *    @access public   *   *************************************************************/   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 ]);              }          }      }  }  /**************************************************************   *   *    将数组转换为JSON字符串(兼容中文)   *    @param    array    $array        要转换的数组   *    @return string        转换得到的json字符串   *    @access public   *   *************************************************************/   function  JSON( $array ) {      arrayRecursive( $array ,  'urlencode' , true);       $json  = json_encode( $array );       return  urldecode( $json );  } 

查看更多关于PHP JSON_DECODE/JSON_ENCODE中文内容为NULL或乱码 - php函的详细内容...

  阅读:36次