最近在接口代码当中用到过json_encode,在网上找到说json_encode编码设置为UTF-8中文就不会乱码,经验证这办法确实是有效果的,但是不知道为什么,代码在用过一段时间之后就不太管用了。以下是自己的解决json_encode的办法。有更好的方法请分享出来吧!
第一种:
这种简单的做一个代码转换,urlcode之后再返回所需数组
我代码这样就足够了。
代码如下 复制代码
第二种:
这种是在网上看到的,然后就是有评论说会出现无限循环的问题,但是这显然很全面的,然后我测试之后也确实有,贴这里仅供参考
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | /************************************************************** * * 使用特定function对数组中所有元素做处理 * @param string &$array 要处理的字符串 * @param string $tocode 编码后 * @param string $oldcode 编码前 * @param string $function 要执行的函数 * @return boolean $apply_to_keys_also 是否也应用到key上 * @return array $array 是否也应用到key上 * @access public * *************************************************************/ function encodeOperations (& $array , $function , $tocode =false, $oldcode =false, $apply_to_keys_also = false) { foreach ( $array as $key => $value ) { (www.jb51.net) if ( is_array ( $value )) { encodeOperations( $array [ $key ], $function , $apply_to_keys_also ); } else { if ( $tocode && $oldcode ) { if (function_exists(mb_convert_encoding)) { $value = mb_convert_encoding( $value , $tocode , $oldcode ); } else { return "error" ; } } $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 ]); } } } return $array ; } /****from:http://www.jb51.net/phper/31/66729.htm********************************************************** * * 将数组转换为JSON字符串(兼容中文) * @param array $array 要转换的数组 * @return string 转换得到的json字符串 * @access public * *************************************************************/ function JSON( $array ) { arrayRecursive( $array , 'urlencode' , true); $json = json_encode( $array ); return urldecode( $json ); } |
对中文返回是null空的话我们需要进行字符转换成uft8或者先使用urlencode进行编译呼。
PS:关于json操作,这里再为大家推荐几款比较实用的json在线工具供大家参考使用:
在线JSON代码检验、检验、美化、格式化工具:
http://tools.jb51.net/code/json
JSON在线格式化工具:
http://tools.jb51.net/code/jsonformat
在线XML/JSON互相转换工具:
http://tools.jb51.net/code/xmljson
json代码在线格式化/美化/压缩/编辑/转换工具:
http://tools.jb51.net/code/jsoncodeformat
在线json压缩/转义工具:
http://tools.jb51.net/code/json_yasuo_trans
C语言风格/HTML/CSS/json代码格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json
联系客服