日期:2014-05-16 浏览次数:20289 次
/** * $json = new Services_JSON(); * * // convert a complexe value to JSON notation, and send it to the browser * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); * $output = $json->encode($value); * * print($output); * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] * * // accept incoming POST data, assumed to be in JSON notation * $input = file_get_contents('php://input', 1000000); * $value = $json->decode($input); * </code> */
<?php /** $json = new json(); $json->decode($string,$type); $json->encode($string); **/ class json { var $at = 0; var $ch = ''; var $text = ''; function encode($arg) { $returnValue = ''; $c = ''; $i = ''; $l = ''; $s = ''; $v = ''; $numeric = true; switch (gettype($arg)) { case 'array': foreach ($arg AS $i => $v) { if (!is_numeric($i)) { $numeric = false; break; } } if ($numeric) { foreach ($arg AS $i => $v) { if (strlen($s) > 0) { $s .= ','; } $s .= $this->encode($arg[$i]); } $returnValue = '[' . $s . ']'; } else { foreach ($arg AS $i => $v) { if (strlen($s) > 0) { $s .= ','; } $s .= $this->encode($i) . ':' . $this->encode($arg[$i]); } $returnValue = '{' . $s . '}'; } break; case 'object': foreach (get_object_vars($arg) AS $i => $v) { $v = $this->encode($v); if (strlen($s) > 0) { $s .= ','; } $s .= $this->encode($i) . ':' . $v; } $returnValue = '{' . $s . '}'; break; case 'integer': case 'double': $returnValue = is_numeric($arg) ? (string) $arg : 'null'; break; case 'string': $returnValue = '"' . strtr($arg, array( "\r" => '\\r', "\n" => '\\n', "\t" => '\\t', "\b" => '\\b', "\f" => '\\f', '\\' => '\\\\', '"' => '\"', "\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002', "\x03" => '\u0003', "\x04" => '\u0004', "\x05" => '\u0005', "\x06" => '\u0006', "\x07" => '\u0007', "\x08" => '\b', "\x0b" => '\u000b', "\x0c" => '\f', "\x0e" => '\u000e', "\x0f" => '\u000f', "\x10" => '\u0010', "\x11" => '\u0011', "\x12" => '\u0012', "\x13" => '\u0013', "\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016', "\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019', "\x1a" => '\u001a', "\x1b" => '\u001b', "\x1c" => '\u001c', "\x1d" => '\u001d', "\x1e" => '\u001e', "\x1f" => '\u001f' )) . '"'; break; case 'boolean': $returnValue = (string) $arg; break; default: $ret