note 82903 deleted from function.json-encode by felipe

From: Date: Thu, 01 May 2008 03:01:09 +0000
Subject: note 82903 deleted from function.json-encode by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-138957@lists.php.net to get a copy of this message
Note Submitter: Steve ---- I've modified jjoss' php2js function to remove the extra whitespace (not needed for machine-readable output) and leave quotes off of non-string variables so that it more closely resembles the output of json_encode. In my testing this function and json_encode return the exact same result. I use this as a substitute if json_encode is not defined, so if anyone finds any differences between this and json_encode I would like to see the corrections. <?php if (!function_exists('json_encode')) { function json_encode($a=false) { if (is_null($a)) return 'null'; if ($a === false) return 'false'; if ($a === true) return 'true'; if (is_scalar($a)) { if (is_float($a)) { // Always use "." for floats. return floatval(str_replace(",", ".", strval($a))); } if (is_string($a)) { static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; } else return $a; } $isList = true; for ($i = 0, reset($a); $i < count($a); $i++, next($a)) { if (key($a) !== $i) { $isList = false; break; } } $result = array(); if ($isList) { foreach ($a as $v) $result[] = php2js($v); return '[' . join(',', $result) . ']'; } else { foreach ($a as $k => $v) $result[] = php2js($k).':'.php2js($v); return '{' . join(',', $result) . '}'; } } } ?>

« previous php.notes (#138957) next »