JSON stands for JavaScript Object Notation. It is a lightweight, text-based data format used to store and transport data.
When exchanging data between a browser and a server (for example, fetching records from an API or sending frontend data to PHP), the data is frequently in JSON format. PHP has built-in, lightning-fast functions to handle JSON.
The json_encode() function is used to encode a PHP value (typically an array or object) into a JSON string format so it can be transmitted.
<?php
// A PHP Associative Array
$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
// Convert it into JSON
echo json_encode($age);
?>
The output looks like this: {"Peter":35,"Ben":37,"Joe":43}. This format can now be perfectly understood by JavaScript on the frontend!
The json_decode() function does the exact opposite. It takes a JSON string sent to the server and converts it into a PHP variable.
By default, json_decode() returns a PHP Object. If you want it to return a PHP Associative Array instead, you must add a second parameter set to true.
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
// Decode into an Object (default)
$obj = json_decode($jsonobj);
echo $obj->Peter . "\n"; // Accessing an object property
// Decode into an Associative Array (true parameter)
$arr = json_decode($jsonobj, true);
echo $arr["Ben"]; // Accessing an array key
?>
Mastering JSON encoding and decoding is a critical step in building REST APIs with PHP!
Which function is used to convert a PHP array into a JSON string?