JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. PHP has built-in functions to handle JSON data efficiently.
JSON is a text-based format used to represent structured data. It is the industry standard for sending data from a server to a web page (via AJAX) or between different web services (APIs).
The json_encode() function is used to convert a PHP array or object into a JSON string.
<?php
$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
// Convert PHP associative array to JSON string
echo json_encode($age);
// Output: {"Peter":35,"Ben":37,"Joe":43}
?>
The json_decode() function is used to convert a JSON string back into a PHP object or an associative array.
By default, json_decode() returns an object.
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$obj = json_decode($jsonobj);
echo $obj->Peter; // Accessing as object property
?>
If you pass true as the second parameter, it returns an associative array instead of an object.
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$arr = json_decode($jsonobj, true);
echo $arr["Peter"]; // Accessing as array element
?>
Once you've decoded the JSON into a PHP array, you can loop through it using foreach.
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$arr = json_decode($jsonobj, true);
foreach($arr as $key => $value) {
echo $key . " is " . $value . " years old.<br>";
}
?>
"). Single quotes are not valid in JSON.
json_decode() determines if you get an object (false) or an associative array (true).json_encode() results.
JSON is the foundation for asynchronous communication. Next, we'll see how to use it with **PHP AJAX** to create faster, smoother user experiences.