YesYo.com MintState Forums
뒤로    YesYo.com MintState BBS > Tech > PHP
검색
멤버이름    오토
비밀번호 
 

[Function] json_encode(), json_decode()

페이지 정보

작성자 MintState 댓글 0건 조회 17,533회 작성일 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
<?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));
?>

댓글목록

등록된 댓글이 없습니다.

Total 165건 1 페이지
PHP 목록
번호 제목 글쓴이 조회 날짜
165 MintState 337 05-17
164 MintState 380 05-11
163 MintState 822 04-05
162 MintState 725 04-03
161 MintState 1074 01-18
160 MintState 1378 08-08
159 MintState 4728 07-31
158 MintState 1509 05-29
157 MintState 1738 02-22
156 MintState 1909 02-21
155 MintState 4234 11-12
154 MintState 3622 12-08
153 MintState 6277 02-26
152 MintState 8794 01-22
151 MintState 6024 07-27
150 MintState 6588 02-10
149 MintState 6941 10-21
148 MintState 9500 05-02
147 MintState 8347 04-18
146 MintState 8473 04-17
145 MintState 8507 04-17
144 MintState 8447 03-14
143 MintState 8436 03-04
142 MintState 9951 01-18
141 MintState 10547 07-02
게시물 검색
모바일 버전으로 보기
CopyRight ©2004 - 2018, YesYo.com MintState. ™