<?PHPfunction__json_encode ($data ) { if(Is_array($data) ||Is_object($data) ) { $islist=Is_array($data) && (Emptyempty ($data) ||Array_keys($data) ===Range(0,Count($data)-1) ); if($islist ) { $json= ' ['. Implode (', ', Array_map (' __json_encode ', $data)). ‘]‘; } Else { $items=Array(); foreach($data as $key=$value ) { $items[] = __json_encode ("$key") . ‘:‘ . __json_encode ($value); } $json= ' {'.implode(‘,‘,$items) . ‘}‘; } } ElseIf(is_string($data) ) { #Escape non-printable or non-ascii characters. #I also put the \ character first, as suggested in comments on the ' addclashes ' page. $string= ' "'.addcslashes($data, "\\\" \n\r\t/".CHR(8).CHR(12)). ‘"‘; $json= ' '; $len=strlen($string); #Convert UTF-8 to hexadecimal codepoints. for($i= 0;$i<$len;$i++ ) { $char=$string[$i]; $c 1=Ord($char); #Single byte; if($c 1<128 ) { $json.= ($c 1> 31)?$char:sprintf("\\u%04x",$c 1); Continue; } #Double byte $c 2=Ord($string[++$i]); if( ($c 1& 32) = = = 0) {Reprint Please indicate the source, Zhiyong's personal blog! $json.=sprintf("\\u%04x", ($c 1–192) * 64 +$c 2–128); Continue; } #Triple $c 3=Ord($string[++$i]); if( ($c 1& 16) = = = 0 ) { $json.=sprintf("\\u%04x", ($c 1–224) <<12) + (($c 2–128) << 6) + ($c 3–128)); Continue; } #Quadruple $c 4=Ord($string[++$i]); if( ($c 1& 8) = = = 0 ) { $u= (($c 1&) << 2) + (($c 2>>4) & 3) –1; $w 1= (54<<10) + ($u<<6) + (($c 2&) << 2) + (($c 3>>4) & 3); $w 2= (55<<10) + (($c 3& <<6) + ($c 4-128); $json.=sprintf("\\u%04x\\u%04x",$w 1,$w 2); } } } Else { #int, floats, bools, null $json=Strtolower(Var_export($data,true )); } return $json; } ?>
PHP implementation JSON