php中json_encode UTF-8中文乱码的更好解决方法_php技巧

WBOY
Release: 2016-05-16 20:35:31
Original
883 people have browsed it

最近在接口代码当中用到过json_encode,在网上找到说json_encode编码设置为UTF-8中文就不会乱码,经验证这办法确实是有效果的,但是不知道为什么,代码在用过一段时间之后就不太管用了。以下是自己的解决json_encode的办法。有更好的方法请分享出来吧!

第一种:

这种简单的做一个代码转换,urlcode之后再返回所需数组

我代码这样就足够了。

代码如下 复制代码

public static function encodeOperations ($array)

{

foreach ((array)$array as $key => $value) {

if (is_array($value)) {

encodeOperations($array[$key]);

} else {

$array[$key] = urlencode(mb_convert_encoding($value,'UTF-8','GBK'));

}

}

return $array;

}
Copy after login

第二种:

这种是在网上看到的,然后就是有评论说会出现无限循环的问题,但是这显然很全面的,然后我测试之后也确实有,贴这里仅供参考

代码如下

/**************************************************************

*

* 使用特定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);

}
Copy after login

对中文返回是null空的话我们需要进行字符转换成uft8或者先使用urlencode进行编译呼。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!