Home >php教程 >PHP源码 >json_encode 编码,对中文友好.

json_encode 编码,对中文友好.

PHP中文网
PHP中文网Original
2016-05-25 17:05:011218browse


function jsonx_encode($array) {
	static $replace=array();
	if(!$replace) {
		for($i=0; $i < 0x20; $i++) {
			//$t = $find[$i];
			$t = chr($i);
			$replace[$t] = sprintf("\\u%04x",$i);
		}
		$replace["\\"]="\\\\";
		$replace["\""]="\\\"";
		$replace["\t"]="\\t";
		$replace["\r"]="\\r";
		$replace["\n"]="\\n";
		$replace["\x0C"]="\\f";
		$replace["\x08"]="\\b";
	}

	$str = &#39;&#39;;
	if(is_array($array) || is_object($array)) {
		$array = (array) $array;
		$is_o = array_keys($array) !== range(0, count($array) - 1);
		$str .= ($is_o ? "{" : &#39;[&#39;);
		$is_start=0;
		foreach($array as $k => $v) {
			$str .= ($is_start ? "," : &#39;&#39;);
			$is_start =1;
			if($is_o){
				$str .= &#39;"&#39;;
				$str .= strtr($k, $replace);
				$str .= &#39;":&#39;;
			}
			$t = __FUNCTION__;
			$str .= $t($v);
		}
		$str .= ($is_o ? "}" : &#39;]&#39;);
	}
	elseif(is_bool($array)) {
		$str .= ($array ? "true" : "false");
	}
	elseif(is_string($array)) {
		$str .= &#39;"&#39;;
		$str .= strtr($array, $replace);
		$str .= &#39;"&#39;;
	}
	elseif(is_numeric($array)) {
		$str .= $array;
	}
	else{
		$str .= &#39;null&#39;;
	}
	return $str;
}

                   

Statement:
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
Previous article:jq 添加删除classNext article:中文分词API