Working with JSON in PHP (API Ready)
Encode and decode JSON, return JSON responses, and build API-style endpoints.
Sophia Reynolds
October 15, 2025
5.9k241
JSON is the language of APIs. PHP works with JSON very easily.
Decode JSON (string to PHP array)
$json = '{"name":"Emma","age":28}';
$data = json_decode($json, true);
echo $data['name'];
The true means “convert to associative array”.
Encode JSON (PHP array to JSON string)
$user = ["name" => "Emma", "age" => 28];
echo json_encode($user);
Return JSON response (API style)
<?php
header('Content-Type: application/json');
$response = ["status" => "ok", "message" => "Hello API"];
echo json_encode($response);
?>
Graph idea: JSON pipeline
flowchart LR
A[Client sends JSON] --> B[PHP json_decode]
B --> C[Process in PHP]
C --> D[PHP json_encode]
D --> E[Client receives JSON]
Next: Connect PHP to MySQL using PDO, the safe modern way.
#PHP#JSON#Beginner