<?php // $Id: json_encode.php 3 2010-10-02 14:56:27Z mashiki $
/**
 * json_encode: use this  for early version(<5.2) of php
 *     which support "multibyte" but doesn't support "json_encode".
 * 
 * Modified by mashiki 2008,2009
 * 
 * Original written by Yi-Ren Chen at NCTU CSIE as php_json_encode()
 *  User Contributed Notes 02-May-2007 01:55 in PHP online manual
 */
function json_encode($val) {
	if (is_numeric($val)) return $val;
	if (is_bool($val)) return $val?'true':'false';
	if (is_array($val)) {
		$len = count($val);
		for($ii=0; $ii<$len && isset($val[$ii]); ++$ii) {}
		$temp = array();
		if($len==$ii) {
			for($i=0;$i<$len;$i++) {
				$temp[] = sprintf("%s", json_encode($val[$i]));
			}
			return '['. implode(",",$temp) .']';
		} else {
			foreach($val as $key => $item) {
				$temp[] = sprintf("\"%s\":%s", $key, json_encode($item));
			}
			return '{'. implode(",", $temp) .'}';
		}
	}
	// else string
	static $from = array('\\',  "\n", "\r", '"');
	static $to   = array('\\\\','\\n','\\r','\\"');
	static $cmap = array(0x80, 0xFFFF, 0, 0xFFFF);
	return '"'. preg_replace_callback(
		'/&#([0-9]+);/',
		create_function('$match','return sprintf("\\u%04x", $match[1]);'),
		mb_encode_numericentity(str_replace($from, $to, $val), $cmap, 'UTF-8')
	) . '"';
}
?>
