복붙노트

PHP JSON 다루기

PHP

PHP JSON 다루기

PHP 5.2 이상부터 json_decode, json_encode 함수가 들어왔습니다.
즉 5.1 이하버전, 4 버전에서는 json_decode, json_encode 함수가 없습니다.
그럴 때를 대비해서 능력자들이 json_decode 함수를 만들어 놓았으니 아래에 참고하세요.

PHP 5.2 이상

JSON 디코딩하기

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';  

var_dump(json_decode($json));  

/*  
object(stdClass)#1 (5) {  
["a"] => int(1)  
["b"] => int(2)  
["c"] => int(3)  
["d"] => int(4)  
["e"] => int(5)  
}  
*/  

var_dump(json_decode($json, true));  
/*  
array(5) {  
["a"] => int(1)  
["b"] => int(2)  
["c"] => int(3)  
["d"] => int(4)  
["e"] => int(5)  
}  
*/  

json_decode(json) 일 경우 JSON 객체를 리턴합니다.
json_decode(json, true) 일 경우 배열 객체를 리턴합니다.

JSON 인코딩하기

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);  
json_encode($arr);  

/*  
{"a":1,"b":2,"c":3,"d":4,"e":5}  
*/  

간단하네요.

PHP 5.1 이하

원본 출처는 http://mike.teczno.com/JSON.tar.gz 입니다.
혹시 몰라서 파일을 첨부했으니 다운로드해 주세요.

JSON.zip

1 다운받은 파일을 적절한 곳에 압축을 풉니다.
2 load_json.php 파일을 생성합니다.

if( !function_exists('json_encode') ) {  
include_once("JSON.php");  
function json_encode($data) {  
$json = new Services_JSON();  
return( $json->encode($data) );  
}  
}  
if( !function_exists('json_decode') ) {  
include_once("JSON.php");  
function json_decode($data) {  
$json = new Services_JSON();  
return( $json->decode($data) );  
}  
}  

3 이제 json을 쓰고자 하는 파일에서 이렇게 사용하세요.

require_once('load_json.php');  

json_decode(JSON파일);  
json_encode(JSON파일);  

json_decode와 json_encode 사용법은 PHP 5.2 버전 이상과 동일합니다.

JSON 유의점

// 다음 문자열은 유효한 자바스크립트이지만, JSON에서는 유효하지 않습니다  

// 이름과 값은 겹따옴표로 감싸야합니다  
// 홑따옴표는 유효하지 않습니다  
$bad_json = "{ 'bar': 'baz' }";  
json_decode($bad_json); // null  

// 이름은 겹따옴표로 감싸야합니다  
$bad_json = '{ bar: "baz" }';  
json_decode($bad_json); // null  

// 따라붙는 쉼표를 허용하지 않습니다  
$bad_json = '{ bar: "baz", }';  
json_decode($bad_json); // null  

출처 : http://php.net/manual/kr/function.json-decode.php

'PHP' 카테고리의 다른 글

PHP 리다이렉트 구현  (0) 2017.11.16
PHP 날짜 차이 계산하기  (0) 2017.11.15
PHP 배열 정렬하기  (0) 2017.11.14
PHP 에서 오류 메세지 보기  (0) 2017.11.13
PHP 타임존 설정  (0) 2017.11.13