[Function] json_encode(), json_decode()
페이지 정보
작성자 MintState 댓글 0건 조회 28,990회 작성일 10-01-13 14:51본문
[Function] json_encode(), json_decode()
json_encode — Returns the JSON representation of a value (PHP 5 >= 5.2.0, PECL json >= 1.2.0)
배열을 json형태로 만들어 주는 함수 입니다. PHP5 이상 버전만 가능합니다.
string json_encode ( mixed $value [, int $options = 0 ] )
Returns a string containing the JSON representation of value .
Parameters
value - The value being encoded. Can be any type except a resource. This function only works with UTF-8 encoded data.
options - Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_FORCE_OBJECT.
Examples
output:
output:
* PHP4 버전은 아래의 함수를 참조하십시오.
json_decode — Decodes a JSON string (PHP 5 >= 5.2.0, PECL json >= 1.2.0)
배열을 json형태로 만들어 주는 함수 입니다. PHP5 이상 버전만 가능합니다.
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 ]] )
Takes a JSON encoded string and converts it into a PHP variable.
Parameters
json - The json string being decoded.
assoc - When TRUE, returned objects will be converted into associative arrays.
depth - User specified recursion depth.
Examples
output:
output:
* PHP4 버전은 아래의 함수를 참조하십시오.
json_encode — Returns the JSON representation of a value (PHP 5 >= 5.2.0, PECL json >= 1.2.0)
배열을 json형태로 만들어 주는 함수 입니다. PHP5 이상 버전만 가능합니다.
string json_encode ( mixed $value [, int $options = 0 ] )
Returns a string containing the JSON representation of value .
Parameters
value - The value being encoded. Can be any type except a resource. This function only works with UTF-8 encoded data.
options - Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_FORCE_OBJECT.
Examples
<?php $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); echo json_encode($arr); ?>
output:
<?php $a = array('<foo>',"'bar'",'"baz"','&blong&'); echo "Normal: ", json_encode($a), "\n"; echo "Tags: ", json_encode($a,JSON_HEX_TAG), "\n"; echo "Apos: ", json_encode($a,JSON_HEX_APOS), "\n"; echo "Quot: ", json_encode($a,JSON_HEX_QUOT), "\n"; echo "Amp: ", json_encode($a,JSON_HEX_AMP), "\n"; echo "All: ", json_encode($a,JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP), "\n\n"; $b = array(); echo "Empty array output as array: ", json_encode($b), "\n"; echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n"; $c = array(array(1,2,3)); echo "Non-associative array output as array: ", json_encode($c), "\n"; echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n"; ?>
output:
* PHP4 버전은 아래의 함수를 참조하십시오.
<?php /* Convert PHP array to JSON -- Using: - on server side: echo(arr2json([PHP array])) - on client side(JavaScript): var obj = eval('(' + [XMLHTTPRequest.responseText] + ')'); */ function arr2json($arr){ foreach($arr as $k=>&$val) $json[] = $k.':'.php2js($val); if(count($json) > 0) return '{'.implode(',', $json).'}'; else return ''; } function php2js($val){ if(is_array($val)) return arr2json($val); if(is_string($val)) return '"'.addslashes($val).'"'; if(is_bool($val)) return 'Boolean('.(int) $val.')'; if(is_null($val)) return '""'; return $val; } ?>
<? 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)) { // MintState Insert $a = preg_replace('{(</)(script)}i', "$1'+'$2", $a); // All scalars are converted to strings to avoid indeterminism. // PHP's "1" and 1 are equal for all PHP operators, but // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend, // we should get the same result in the JS frontend (string). // Character replacements for JSON. 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[] = json_encode($v); return '[ ' . join(', ', $result) . ' ]'; } else { foreach ($a as $k => $v) $result[] = json_encode($k).': '.json_encode($v); return '{ ' . join(', ', $result) . ' }'; } } } ?>
json_decode — Decodes a JSON string (PHP 5 >= 5.2.0, PECL json >= 1.2.0)
배열을 json형태로 만들어 주는 함수 입니다. PHP5 이상 버전만 가능합니다.
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 ]] )
Takes a JSON encoded string and converts it into a PHP variable.
Parameters
json - The json string being decoded.
assoc - When TRUE, returned objects will be converted into associative arrays.
depth - User specified recursion depth.
Examples
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); var_dump(json_decode($json, true)); ?>
output:
<?php $json = '{"foo-bar": 12345}'; $obj = json_decode($json); print $obj->{'foo-bar'}; // 12345 ?>
<?php // Encode the data. $json = json_encode( array( 1 => array( 'English' => array( 'One', 'January' ), 'French' => array( 'Une', 'Janvier' ) ) ) ); // Define the errors. $json_errors = array( JSON_ERROR_NONE => 'No error has occurred', JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded', JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded', JSON_ERROR_SYNTAX => 'Syntax error', ); // Show the errors for different depths. foreach(range(4, 3, -1) as $depth) { var_dump(json_decode($json, True, $depth)); echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL; } ?>
output:
* PHP4 버전은 아래의 함수를 참조하십시오.
<?php if ( !function_exists('json_decode') ){ function json_decode($json) { // Author: walidator.info 2009 $comment = false; $out = '$x='; for ($i=0; $i<strlen($json); $i++) { if (!$comment) { if ($json[$i] == '{') $out .= ' array('; else if ($json[$i] == '}') $out .= ')'; else if ($json[$i] == ':') $out .= '=>'; else $out .= $json[$i]; } else $out .= $json[$i]; if ($json[$i] == '"') $comment = !$comment; } eval($out . ';'); return $x; } } $json_data = '{"response": { "Text":"Hello there" }, "Details": null, "Status": 200} '; print_r(json_decode($json_data)); ?>
|
댓글목록
등록된 댓글이 없습니다.