PHP JSON
JSON (JavaScript Object Notation) is a lightweight text format for exchanging data, commonly used by web APIs. PHP can convert PHP arrays and objects into JSON strings using json_encode(), and parse JSON strings back into PHP data using json_decode().
JSON is language-independent, which makes it ideal for communication between a PHP backend and a JavaScript frontend, or between different services and applications.
json_encode($data);
json_decode($json, true);Encoding to JSON
json_encode($array) converts a PHP array or object into a JSON-formatted string, which can then be sent as an API response or saved to a file.
Decoding from JSON
json_decode($json, true) converts a JSON string back into a PHP associative array; omitting true returns a plain object instead.
<?php
$data = ["name" => "Amy", "age" => 25];
echo json_encode($data);
?>{"name":"Amy","age":25}json_encode() converts the associative array into a JSON object string.
<?php
$json = '{"name":"Amy","age":25}';
$data = json_decode($json, true);
echo $data["name"];
?>Amyjson_decode() with true converts the JSON string back into a PHP associative array.
Key points
- json_encode() converts PHP data into a JSON string.
- json_decode() converts a JSON string back into PHP data.
- Passing true to json_decode() returns an associative array instead of an object.
- JSON is widely used for APIs and data exchange between systems.
