PHP and JSON
JSON stands for JavaScript Object Notation. It is a lightweight format for storing and transporting data. Since JSON is a text-based format, it can easily be sent to and from a server, and used as a data format by any programming language.
1. PHP and JSON Functions
PHP has two built-in functions to handle JSON data:
json_encode(): Converts a PHP array or object into a JSON string.
json_decode(): Converts a JSON string into a PHP object or an associative array.
2. PHP - json_encode()
This function is used to encode a value to JSON format. It is most commonly used when you want to send data from your PHP server to a JavaScript frontend.
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo json_encode($cars);
// Output: ["Volvo","BMW","Toyota"]
$age = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
echo json_encode($age);
// Output: {"Peter":35,"Ben":37,"Joe":43}
?>
3. PHP - json_decode()
This function is used to decode a JSON string into a PHP variable. By default, it returns an object.
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$obj = json_decode($jsonobj);
echo $obj->Peter; // Accessing object property
?>
4. Decoding into an Associative Array
If you want json_decode() to return an associative array instead of an object, you must pass true as the second parameter.
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$arr = json_decode($jsonobj, true);
echo $arr["Peter"]; // Accessing array element
?>
5. Looping Through Values
You can loop through the decoded data using a foreach loop, just like a regular PHP array.
<?php
$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
$arr = json_decode($jsonobj, true);
foreach($arr as $key => $value) {
echo $key . " => " . $value . "<br>";
}
?>
Tip: JSON is the "language of the web." Whenever you work with APIs (like Google Maps or Weather APIs), you will almost always receive the data in JSON format and use json_decode() to process it in PHP.