PHP json_encode()

Jmnote (토론 | 기여)님의 2020년 2월 5일 (수) 16:12 판 (→‎예시)

1 개요

PHP json_encode()
  • PHP Array 또는 String 따위를 JSON 문자열로 변환하는 PHP 함수
  • 첫 번째 명령어 $value는 JSON으로 묶을 Array 또는 String 값이다. String일 경우 곁따옴표가 양쪽에 붙는다.
  • 두 번째 명령어 $options는 이스케이프할 문자를 설정할 수 있다.
JSON 상수(JSON_HEX_QUOT, JSON_HEX_TAG, ...)로 구성되는 비트마스크 설정
기본값은 0 (비트마스크 없음). 주로 이 기본값을 사용한다.
형식
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

2 예시

echo json_encode( ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5] ); # {"a":1,"b":2,"c":3,"d":4,"e":5}
echo json_encode( ['apple', 'banana', 'A가★あ中!@'] ); # ["apple","banana","A\uac00\u2605\u3042\u4e2d!@"]
echo json_encode( ['fruit1' => 'apple', 'fruit2' => 'banana', 'test' => ['utf8' => 'A가★あ中!@']] ); # {"fruit1":"apple","fruit2":"banana","test":{"utf8":"A\uac00\u2605\u3042\u4e2d!@"}}

3 예시: true/false

  • 자료형이 문자열로 변환된다.
var_dump( json_encode(true) );
# string(4) "true"
var_dump( json_encode(false) );
# string(5) "false"

4 기타

function json_readable_encode($in, $indent = 0, $from_array = false) {
    $_myself = __FUNCTION__;
    $_escape = function ($str) {
        return preg_replace("!([\b\t\n\r\f\"\\'])!", "\\\\\\1", $str);
    };

    $out = '';
    foreach ($in as $key=>$value) {
        $out .= str_repeat("\t", $indent + 1);
        $out .= "\"".$_escape((string)$key)."\": ";
        if (is_object($value) || is_array($value)) {
            $out .= "\n";
            $out .= $_myself($value, $indent + 1);
        }
        elseif (is_bool($value)) $out .= $value ? 'true' : 'false';
        elseif (is_null($value)) $out .= 'null';
        elseif (is_string($value)) $out .= "\"" . $_escape($value) ."\"";
        else $out .= $value;
        $out .= ",\n";
    }
    if (!empty($out)) $out = substr($out, 0, -2);
    $out = str_repeat("\t", $indent) . "{\n" . $out;
    $out .= "\n" . str_repeat("\t", $indent) . "}";

    return $out;
}

5 같이 보기

6 참고

  1. Generates a storable representation of a value
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}