Programming with JSON in PHP
JSON using built-in functions to encode PHP data into JSON format (serialization) and decode JSON data into PHP format (deserialization).
Syntax
json_encode(mixed $value, int $options = 0, int $depth = 512): string|false
json_decode(string $json, bool $assoc = false, int $depth = 512, int $options = 0): mixed
Example
// Encoding a PHP array to JSON
$students = [
[
"name" => "John",
"age" => 18,
"major" => "Computer Science",
"grades" => [90, 85, 95]
],
[
"name" => "Mary",
"age" => 19,
"major" => "Engineering",
"grades" => [95, 92, 88]
]
];
$json = json_encode($students);
// Decoding a JSON string to a PHP array
$array = json_decode($json, true);
echo "<pre>";
print_r($array);
echo "</pre>";
Output
Array
(
[0] => Array
(
[name] => John
[age] => 18
[major] => Computer Science
[grades] => Array
(
[0] => 90
[1] => 85
[2] => 95
)
)
[1] => Array
(
[name] => Mary
[age] => 19
[major] => Engineering
[grades] => Array
(
[0] => 95
[1] => 92
[2] => 88
)
)
)
Explanation
json_encode
function is used to encode a PHP array to JSON format.json_decode
function is used to decode a JSON string to a PHP array.- The second parameter of
json_decode
function, if set totrue
, will return an associative array. - We use the
print_r
function to print the PHP array in a human-readable format.
Use
You can use JSON in PHP to:
- Send data between the client and server in AJAX/HTTP requests.
- Store and retrieve data from a database in JSON format.
- Exchange data between web services.
- Save configuration settings in JSON format.
Important Points
- JSON stands for JavaScript Object Notation.
- JSON format is lightweight and easy to parse and generate.
- PHP provides two functions,
json_encode
andjson_decode
, for encoding and decoding JSON data. - By default,
json_decode
returns an object. Usetrue
as the second parameter to get an associative array. - JSON data must be UTF-8 encoded.
Summary
In this tutorial, we learned how to use JSON in PHP to encode and decode data. We also saw how to send and receive data in JSON format in AJAX requests, work with JSON in databases, and exchange data between web services.