Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 2 of 6

JSON - Encoding, Decoding & API Data

JSON is the universal format for data exchange between PHP backends and frontends, mobile apps, and third-party APIs. PHP's json_encode and json_decode handle the conversion - but understanding flags, handling encoding errors, and mapping to typed objects is essential for robust API code.

12 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

JSON Encoding, Decoding & Error Handling

JSON Encoding, Decoding & Error Handling
<?php
declare(strict_types=1);

// ── json_encode - PHP → JSON ──────────────────────────────────
$data = [
    "id"         => 1,
    "title"      => "PHP & JSON - Complete Guide",
    "tags"       => ["php", "json", "api"],
    "published"  => true,
    "views"      => 1250,
    "price"      => null,
    "created_at" => "2026-03-20T08:00:00+00:00",
];

// Default output
$json = json_encode($data);
// {"id":1,"title":"PHP & JSON — Complete Guide","tags":["php","json","api"]...}

// Pretty-print for debugging / files
$pretty = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

// JSON_UNESCAPED_UNICODE  - don't escape non-ASCII as \uXXXX (shorter, readable)
// JSON_UNESCAPED_SLASHES  - don't escape / as \/ (cleaner URLs)
// JSON_PRETTY_PRINT       - human-readable with indentation
// JSON_HEX_TAG            - encode < > as \u003C \u003E (XSS-safe in scripts)
// JSON_THROW_ON_ERROR     - throw JsonException instead of returning false

// ✅ Use JSON_THROW_ON_ERROR - never silently fail
try {
    $json = json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
} catch (JsonException $e) {
    error_log("JSON encode failed: " . $e->getMessage());
    throw new RuntimeException("Failed to serialize data.");
}

// ── json_decode - JSON → PHP ──────────────────────────────────
$apiResponse = '{"id":1,"title":"PHP Basics","tags":["php","web"],"published":true}';

// As associative array (recommended for most use cases)
$decoded = json_decode($apiResponse, associative: true, flags: JSON_THROW_ON_ERROR);
echo $decoded["title"];   // "PHP Basics"

// As object (stdClass)
$obj = json_decode($apiResponse, associative: false);
echo $obj->title;          // "PHP Basics"

// ── API response wrapper ───────────────────────────────────────
class JsonResponse {
    public function __construct(
        private readonly mixed $data,
        private readonly int   $status = 200,
        private readonly array $headers = [],
    ) {}

    public function send(): void {
        http_response_code($this->status);
        header("Content-Type: application/json; charset=UTF-8");
        foreach ($this->headers as $name => $value) {
            header("$name: $value");
        }
        echo json_encode([
            "success" => $this->status < 400,
            "data"    => $this->data,
        ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    public static function success(mixed $data, int $status = 200): static {
        return new static($data, $status);
    }

    public static function error(string $message, int $status = 400): static {
        return new static(["message" => $message], $status);
    }
}

// ── Reading config/settings from JSON file ─────────────────────
function loadConfig(string $path): array {
    if (!file_exists($path)) throw new RuntimeException("Config file not found: $path");
    $raw = file_get_contents($path);
    if ($raw === false) throw new RuntimeException("Could not read config.");
    return json_decode($raw, associative: true, flags: JSON_THROW_ON_ERROR);
}

$config = loadConfig(__DIR__ . "/../config/settings.json");

Quick Quiz

Tip

Tip

Practice JSON Encoding Decoding API Data in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for JSON - Encoding, Decoding & API Data

Practice Task

Note

Practice Task - (1) Write a working example of JSON Encoding Decoding API Data from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with JSON Encoding Decoding API Data is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/6 done