PHP JSON — Complete Guide to JSON Encoding and Decoding
In this tutorial, you will learn about PHP JSON. We cover key concepts, practical examples, and best practices to help you master this topic.
PHP provides json_encode and json_decode functions for converting between PHP data structures and JSON format, essential for API development and data interchange.
What You'll Learn
By the end of this tutorial, you'll encode PHP arrays and objects to JSON, decode JSON to PHP, handle errors, format output, validate JSON, and build JSON APIs.
Why JSON Matters
JSON is the universal data format for web APIs, configuration files, and data storage. Every modern PHP application interacts with JSON for REST APIs, AJAX requests, and data exchange.
Real-World Use
An API endpoint returns user data as JSON. The PHP controller queries the database, formats the result as an associative array, and encodes it as JSON for the frontend React app.
JSON Learning Path
flowchart LR
A[Sessions] --> B[JSON]
B --> C[File Handling]
C --> D[Errors]
D --> E[Exceptions]
A --> F{You Are Here}
style F fill:#f90,color:#fff
Encoding to JSON
<?php
$user = [
"id" => 1,
"name" => "Alice",
"email" => "alice@example.com",
"roles" => ["admin", "editor"],
"active" => true,
"preferences" => ["theme" => "dark", "notifications" => true]
];
echo json_encode($user);
// {"id":1,"name":"Alice","email":"alice@example.com",...}
Decoding JSON
<?php
$json = '{"name":"Alice","age":25,"city":"Mumbai"}';
$array = json_decode($json, true); // Associative array
$object = json_decode($json); // stdClass object
echo $array["name"]; // Alice
echo $object->name; // Alice
JSON Options
<?php
$data = ["name" => "Alice", "age" => 25, "score" => null];
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
/* Output:
{
"name": "Alice",
"age": 25,
"score": null
}
*/
Error Handling
<?php
$json = '{"name": "Alice", incomplete}';
$result = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Error: " . json_last_error_msg();
// JSON Error: Syntax error
}
JSON API Response
<?php
function jsonResponse(mixed $data, int $statusCode = 200): void {
http_response_code($statusCode);
header("Content-Type: application/json; charset=utf-8");
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
exit;
}
jsonResponse(["success" => true, "data" => ["id" => 1, "name" => "Product"]]);
Reading JSON Files
<?php
// config.json: {"db_host": "localhost", "db_port": 3306}
$config = json_decode(file_get_contents("config.json"), true);
echo $config["db_host"]; // localhost
// Writing JSON to file
$data = ["updated" => time(), "status" => "ok"];
file_put_contents("status.json", json_encode($data, JSON_PRETTY_PRINT));
Common Mistakes
1. Not Handling Large Integers
PHP integers larger than PHP_INT_MAX become floats. Use JSON_BIGINT_AS_STRING option for large numbers.
2. Assuming json_decode Returns Array
Without true flag, json_decode returns stdClass objects. Be consistent with the second parameter.
3. Not Checking json_last_error
Invalid JSON returns null without error if JSON_THROW_ON_ERROR is not set. Always check for errors.
4. UTF-8 Issues
json_encode requires UTF-8 encoded strings. Non-UTF-8 data produces errors. Use utf8_encode() or mb_convert_encoding().
5. Encoding Private Properties
Private and protected properties are included in json_encode unless JsonSerializable interface is implemented.
Practice Questions
1. What is the difference between json_decode($str) and json_decode($str, true)?
Without true, returns stdClass objects. With true, returns associative arrays.
2. How do you make JSON output human-readable?
Use JSON_PRETTY_PRINT flag in json_encode. Use JSON_UNESCAPED_UNICODE for non-ASCII characters.
3. How do you check if JSON decoding failed?
Check json_last_error() !== JSON_ERROR_NONE or use try/catch with JSON_THROW_ON_ERROR.
4. How do you handle JSON from a POST request?
$data = json_decode(file_get_contents("php://input"), true);
5. Challenge: Create a PHP function that validates JSON data against a required structure.
<?php
function validateJson(string $json, array $requiredKeys): array {
$data = json_decode($json, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return ["valid" => false, "error" => json_last_error_msg()];
}
$missing = array_diff($requiredKeys, array_keys($data));
return [
"valid" => empty($missing),
"data" => $data,
"missing" => $missing
];
}
print_r(validateJson('{"name":"Alice"}', ["name", "email"]));
// ["valid" => false, "missing" => ["email"]]
FAQ
Mini Project: JSON Config Loader
Build a configuration loader that reads JSON config files with validation.
<?php
function loadConfig(string $filePath): array {
if (!file_exists($filePath)) throw new RuntimeException("Config not found: $filePath");
$content = file_get_contents($filePath);
$config = json_decode($content, true, 512, JSON_THROW_ON_ERROR);
$required = ["db_host", "db_name", "app_secret"];
foreach ($required as $key) {
if (!isset($config[$key])) throw new RuntimeException("Missing config: $key");
}
return $config;
}
$config = loadConfig("config.json");
echo $config["db_host"];
What's Next
PHP File Handling PHP Errors PHP Exceptions
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro