Home >Backend Development >PHP Tutorial >JavaScript Object Notation (JSON) for php

JavaScript Object Notation (JSON) for php

伊谢尔伦
伊谢尔伦Original
2016-11-21 17:52:121019browse

Since PHP 5.2.0, the JSON extension is built-in and compiled into PHP by default.

JSON serialization interface JsonSerializable

Classes that implement JsonSerializable can customize their JSON representation when json_encode().

JsonSerializable::jsonSerialize — Specify the data that needs to be serialized into JSON

Example #1 Returns an array

<?php
    class ArrayValue implements JsonSerializable {
        public function __construct(array $array) {
            $this->array = $array;
        }
        public function jsonSerialize() {
            return $this->array;
        }
    }
    $array = [1, 2, 3];
    echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

The above routine will output:

[
    1,
    2,
    3
]

Example #2 Returns an associative array

<?php
    class ArrayValue implements JsonSerializable {
        public function __construct(array $array) {
            $this->array = $array;
        }
        public function jsonSerialize() {
            return $this->array;
        }
    }
    $array = [&#39;foo&#39; => &#39;bar&#39;, &#39;quux&#39; => &#39;baz&#39;];
    echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT);
?>

The above routine will Output:

{
    "foo": "bar",
    "quux": "baz"
}

Example #3 Returns an integer number

<?php
    class IntegerValue implements JsonSerializable {
        public function __construct($number) {
            $this->number = (integer) $number;
        }
        public function jsonSerialize() {
            return $this->number;
        }
    }
    echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT);
?>

The above routine will output:

1

Example #4 Returns a string

<?php
    class StringValue implements JsonSerializable {
        public function __construct($string) {
            $this->string = (string) $string;
        }
        public function jsonSerialize() {
            return $this->string;
        }
    }
    echo json_encode(new StringValue(&#39;Hello!&#39;), JSON_PRETTY_PRINT);
?>

The above routine will output:

"Hello!"

JSON function

json_decode — Encodes a string in JSON format

json_encode — Encodes a variable in JSON

json_last_error_msg — Returns the error string of the last json_encode() or json_decode() call

json_last_error — Return The last error that occurred


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn