PHP ยท Chapter 34 of 44

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.

Syntax
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.

Example 1 (php)
<?php
  $data = ["name" => "Amy", "age" => 25];
  echo json_encode($data);
?>
Output
{"name":"Amy","age":25}

json_encode() converts the associative array into a JSON object string.

Example 2 (php)
<?php
  $json = '{"name":"Amy","age":25}';
  $data = json_decode($json, true);
  echo $data["name"];
?>
Output
Amy

json_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.
๐Ÿ’ก Note: Set the Content-Type: application/json header when returning JSON from a PHP API endpoint.

๐Ÿ“ Quick Quiz

1. Which function converts a PHP array into a JSON string?

2. What does passing true as the second argument to json_decode() do?

3. What does JSON stand for?