Working with JSON Data in PHP: Encoding and Decoding JSON using `json_encode()` and `json_decode()`
Learn how to effectively handle JSON data in PHP using the `json_encode()` and `json_decode()` functions. This tutorial provides a comprehensive guide to encoding PHP arrays and objects into JSON format and decoding JSON strings into PHP variables, enhancing your PHP skills for data exchange.
Working with JSON in PHP
PHP's JSON Functions: json_encode() and json_decode()
PHP provides built-in functions for handling JSON data: json_encode()
for encoding PHP data into JSON format and json_decode()
for decoding JSON data into PHP variables.
json_encode() Function
The json_encode()
function converts a PHP value (often an array or object) into a JSON string.
Syntax:
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
Example 1:
Code
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Output
{"a":1,"b":2,"c":3,"d":4,"e":5}
Example 2:
Code
<?php
$arr2 = array('firstName' => 'Rahul', 'lastName' => 'Kumar', 'email' => 'rahul@gmail.com');
echo json_encode($arr2);
?>
Output
{"firstName":"Rahul","lastName":"Kumar","email":"rahul@gmail.com"}
json_decode() Function
The json_decode()
function converts a JSON string into a PHP value (either an array or an object, depending on the settings).
Syntax:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
Example 1:
Code
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true)); // true to get an associative array
?>
Output
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
Example 2:
Code
<?php
$json2 = '{"firstName":"Rahul","lastName":"Kumar","email":"rahul@gmail.com"}';
print_r(json_decode($json2, true));
?>
Output
Array
(
[firstName] => Rahul
[lastName] => Kumar
[email] => rahul@gmail.com
)