php json_encode always returns the unicode character 'u...' problem solution

WBOY
Release: 2016-08-08 09:26:13
Original
1742 people have browsed it

最近遇上了一件怪事,前两天写的好好的代码,今天再运行就乱码了。查了一下,不是一般意义的乱码,而是返回的unicode编码的字符。

如汉字:登录失败,经过json_encode之后返回变成:"\u767b\u5f55\u5931\u8d25"

实在气死杂家,找了一通,发现这是个普遍问题,最终解决方法如下:

正常调用json_encode($arr),在echo之间,将这个json数据通过以下函数处理下:

public static function JSON($str){
$json = json_encode($str);
return preg_replace("#\\\u([0-9a-f]+)#ie","iconv('UCS-2','UTF-8', pack('H4', '\\1'))",$json);
}

这样就再也不乱码了。对于高版本php,可以直接加个参数,但对低版本无效,所以只能这样。完整代码如下:

<?php
class util{
	
	
	public static function JSON($str){
		$json = json_encode($str);
		return preg_replace("#\\\u([0-9a-f]+)#ie","iconv('UCS-2','UTF-8', pack('H4', '\\1'))",$json);
	}
	
}

?>
Copy after login

调用示例:

<span>		// echo "登录失败";
			$arr = array ();
			$arr ['code'] = - 1;
			$arr ['message'] = "登录失败";
			echo $arr ['message'];
			$arr ['data'] = "";
			
			return util::JSON ( $arr );</span>
Copy after login
参考:http://stackoverflow.com/questions/6771938/any-way-to-return-php-json-encode-with-encode-utf-8-and-not-unicode

以上就介绍了php json_encode总是返回unicode字符 "\u..."问题 解决,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

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!