JSON (JavaScript Object Notation) is the universal lingua franca of the modern internet. When a PHP backend communicates with a React frontend, a Flutter mobile app, or third-party web services (like Google Maps, Stripe, or Weather APIs), data is exchanged as JSON. PHP provides two native, lightning-fast C-level functions: json_encode() (converting PHP data to JSON) and json_decode() (parsing JSON into PHP arrays/objects).
json_encode()<?php
$student = [
"id" => 1001,
"name" => "Vikram Aditya",
"course" => "BCA",
"skills" => ["PHP 8", "MySQL", "JavaScript"],
"graduated" => false
];
// Standard JSON output
$jsonOutput = json_encode($student);
echo $jsonOutput . "<br><br>";
// Pretty Printed JSON for human readability
$prettyJson = json_encode($student, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
echo "<pre>" . htmlspecialchars($prettyJson) . "</pre>";
?>
json_decode()When reading JSON payloads from API endpoints or frontend AJAX requests:
<?php
$jsonString = '{"brand":"Veewom","course":"PHP 8 Masterclass","duration_weeks":12}';
// 1. Decode into a PHP Associative Array (2nd param = true)
$arr = json_decode($jsonString, true);
echo "Course Name (Array): " . $arr["course"] . "<br>";
// 2. Decode into a PHP Object (2nd param omitted or false)
$obj = json_decode($jsonString);
echo "Course Name (Object): " . $obj->course . "<br>";
?>
json_last_error()Malformed JSON strings (e.g. missing quotes or trailing commas) will fail to decode. Always check for errors in production APIs:
<?php
$badJson = '{"name": "Vikram", "marks": 90, }'; // Invalid trailing comma!
$data = json_decode($badJson, true);
if (json_last_error() !== JSON_ERROR_NONE) {
echo "JSON Parse Error: " . json_last_error_msg();
}
?>
High-Frequency Exam Question:
Q: How does PHP 7.3+ simplify JSON error handling?
A: PHP 7.3 introduced the JSON_THROW_ON_ERROR flag. Instead of manually inspecting json_last_error(), you can pass this flag to automatically throw a catchable JsonException on malformed input:
$data = json_decode($input, true, 512, JSON_THROW_ON_ERROR);.
Exercise 44.1: Fetch public weather JSON data from an online test API using file_get_contents(), decode it with json_decode(), and display the current temperature in an HTML badge.
Exercise 44.2: Write a script that serializes a multidimensional student roster array into JSON and saves it to a students.json file.