PHP JSON

JSON (JavaScript Object Notation) is a lightweight data format widely used to exchange data between servers and web applications, between a PHP backend and a JavaScript frontend, or between different web services (APIs). PHP has built-in functions for encoding PHP data into JSON format and decoding JSON strings back into PHP data structures.

What Is JSON

JSON represents structured data using two constructs: objects (key-value pairs enclosed in curly braces) and arrays (ordered lists enclosed in square brackets). It supports strings, numbers, booleans, null, objects, and arrays.

{
  "name": "Alice",
  "age": 30,
  "email": "alice@example.com",
  "isPremium": true,
  "skills": ["PHP", "MySQL", "HTML"],
  "address": {
    "city": "New York",
    "country": "USA"
  }
}

json_encode() — PHP to JSON

json_encode() converts a PHP value (array or object) into a JSON string.

<?php
  $user = [
    "name"      => "Alice",
    "age"       => 30,
    "email"     => "alice@example.com",
    "isPremium" => true,
    "skills"    => ["PHP", "MySQL", "HTML"],
  ];

  $json = json_encode($user);
  echo $json;
  // {"name":"Alice","age":30,"email":"alice@example.com","isPremium":true,"skills":["PHP","MySQL","HTML"]}
?>

Pretty-Printing JSON

<?php
  $json = json_encode($user, JSON_PRETTY_PRINT);
  echo $json;
  /*
  {
      "name": "Alice",
      "age": 30,
      "email": "alice@example.com",
      "isPremium": true,
      "skills": [
          "PHP",
          "MySQL",
          "HTML"
      ]
  }
  */
?>

Useful json_encode() Flags

FlagEffect
JSON_PRETTY_PRINTFormats the output with indentation and newlines
JSON_UNESCAPED_UNICODEOutputs Unicode characters as-is instead of \uXXXX
JSON_UNESCAPED_SLASHESDoes not escape forward slashes
JSON_NUMERIC_CHECKConverts numeric strings to numbers
JSON_THROW_ON_ERRORThrows JsonException on encoding errors
<?php
  $data = ["url" => "https://example.com/page", "city" => "São Paulo"];

  echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  // {"url":"https://example.com/page","city":"São Paulo"}
?>

json_decode() — JSON to PHP

json_decode() converts a JSON string back into PHP data. By default it returns an object; passing true as the second argument returns an associative array instead.

<?php
  $jsonString = '{"name":"Bob","age":25,"skills":["Python","JavaScript"]}';

  // Decode to associative array (true = associative)
  $data = json_decode($jsonString, true);

  echo $data['name'];       // Bob
  echo $data['age'];        // 25
  echo $data['skills'][0];  // Python

  // Decode to object (default)
  $obj = json_decode($jsonString);
  echo $obj->name;          // Bob
  echo $obj->skills[1];     // JavaScript
?>

Handling JSON Errors

<?php
  $badJson = "{ name: Alice }";   // Invalid JSON (keys must be quoted)

  $data = json_decode($badJson, true);

  if (json_last_error() !== JSON_ERROR_NONE) {
    echo "JSON error: " . json_last_error_msg();
    // JSON error: Syntax error
  }
?>

In PHP 7.3 and later, use JSON_THROW_ON_ERROR for cleaner error handling with exceptions:

<?php
  try {
    $data = json_decode($badJson, true, 512, JSON_THROW_ON_ERROR);
  } catch (JsonException $e) {
    echo "Failed to parse JSON: " . $e->getMessage();
  }
?>

Building a JSON API Response

PHP is commonly used to build REST API endpoints that return JSON to a frontend or mobile app.

<?php
  // api/users.php
  header("Content-Type: application/json");
  header("Access-Control-Allow-Origin: *");

  require_once "../config/database.php";

  try {
    $stmt = $pdo->query("SELECT id, username, email FROM users LIMIT 10");
    $users = $stmt->fetchAll();

    echo json_encode([
      "success" => true,
      "count"   => count($users),
      "data"    => $users,
    ], JSON_UNESCAPED_UNICODE);

  } catch (PDOException $e) {
    http_response_code(500);
    echo json_encode([
      "success" => false,
      "error"   => "Database error occurred.",
    ]);
  }
?>

Consuming a JSON API

PHP can also consume external JSON APIs using file_get_contents() or cURL.

<?php
  // Fetch JSON from an external API
  $url = "https://jsonplaceholder.typicode.com/todos/1";

  $response = file_get_contents($url);

  if ($response !== false) {
    $todo = json_decode($response, true);

    echo "Title: " . $todo['title'] . "\n";
    echo "Completed: " . ($todo['completed'] ? 'Yes' : 'No') . "\n";
  } else {
    echo "Failed to fetch data.";
  }
?>

Using cURL for More Control

<?php
  $ch = curl_init("https://jsonplaceholder.typicode.com/posts");

  curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 10,
    CURLOPT_HTTPHEADER     => ["Accept: application/json"],
  ]);

  $response = curl_exec($ch);
  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);

  if ($httpCode === 200) {
    $posts = json_decode($response, true);
    echo "Fetched " . count($posts) . " posts.";
  }
?>

Key Points

  • json_encode() converts a PHP array or object to a JSON string.
  • json_decode() converts a JSON string to a PHP object (default) or associative array (pass true).
  • Check for encoding/decoding errors with json_last_error() and json_last_error_msg(), or use JSON_THROW_ON_ERROR.
  • Always set the Content-Type: application/json header when your PHP script returns JSON to a client.
  • Use JSON_PRETTY_PRINT during development for human-readable output; omit it in production for smaller payload sizes.
  • Use JSON_UNESCAPED_SLASHES and JSON_UNESCAPED_UNICODE when outputting URLs or non-ASCII text.

Leave a Comment

Your email address will not be published. Required fields are marked *