PHP and JSON

PHP and JSON are often used together for web development, especially when you're building APIs or handling data exchange between a server and a client.

Here's a quick overview and example of how they work together:

What is JSON?

  • JSON (JavaScript Object Notation) is a lightweight data-interchange format.

  • It's easy to read/write for humans and easy to parse/generate for machines.

  • Format example:

    { "name": "Alice", "age": 30, "is_member": true }

Working with JSON in PHP

1. Encoding PHP data into JSON

Use json_encode() to convert PHP arrays or objects to JSON format.

<?php $data = [ "name" => "Alice", "age" => 30, "is_member" => true ]; $json = json_encode($data); echo $json; // Output: {"name":"Alice","age":30,"is_member":true} ?>

2. Decoding JSON into PHP

Use json_decode() to convert JSON into a PHP variable.

<?php $json = '{"name":"Alice","age":30,"is_member":true}'; $data = json_decode($json, true); // true returns associative array echo $data["name"]; // Output: Alice ?>

Common Use Case: API Response

<?php header('Content-Type: application/json'); $response = [ "status" => "success", "message" => "Data fetched successfully", "data" => ["id" => 101, "name" => "Alice"] ]; echo json_encode($response); ?>