Home >Backend Development >PHP Tutorial >JavaScript Object Notation (JSON) for php
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 = ['foo' => 'bar', 'quux' => 'baz']; 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('Hello!'), 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