PHPLesson 13 of 13

PHP and JSON

JSON is the text format that apps and servers use to exchange data. It looks like a JavaScript object, which is where the name comes from, and almost every language can read and write it. PHP has built-in functions for both directions, which makes JSON the shortest path between your PHP data and the outside world.

JSON is the text format that apps and servers use to exchange data. It looks like a JavaScript object, which is where the name comes from, and almost every language can read and write it. PHP has built-in functions for both directions, which makes JSON the shortest path between your PHP data and the outside world.

json_encode() turns an array into a JSON string. An associative array becomes an object, an indexed array becomes a list. The function handles nesting, so arrays inside arrays come out correct. The result is a string you can echo, save to a file, or send back to a browser script.

json_decode() does the reverse. It parses a JSON string back into PHP data. By default you get objects, and passing true as the second argument gives you associative arrays instead, which most beginners find easier to work with.

The real-world job of JSON in PHP is APIs: pages that return data instead of HTML. With a few headers and an echo, a PHP file becomes an endpoint that a frontend can fetch. This is the bridge between the PHP server and the JavaScript you already learned.

Encoding and decoding

json_encode returns the string, and json_decode parses it. The second argument of json_decode controls the shape: true means associative arrays, omitted means objects with -> access.

PHP
$user = ["name" => "Aya", "age" => 24];
$json = json_encode($user);
// {"name":"Aya","age":24}

$back = json_decode($json, true);
echo $back["name"]; // Aya

A tiny API endpoint

Set the Content-Type header so the browser knows it is JSON, then echo the encoded data. A fetch call from JavaScript receives this array of products directly.

PHP
header("Content-Type: application/json");
$products = [
  ["id" => 1, "name" => "Shirt", "price" => 1200],
  ["id" => 2, "name" => "Hat", "price" => 900]
];
echo json_encode($products);

Syntax

PHP
<?php
$data = [
  "status" => "ok",
  "items" => ["html", "css", "php"]
];
echo json_encode($data);
?>

json_decode Needs true for Array

json_decode($json) gives object, json_decode($json, true) gives array — choose correctly.

PHP
json_decode($json, true) // array

Good to know

  • json_encode turns arrays into JSON strings.
  • json_decode parses JSON back, with true giving arrays.
  • A Content-Type header plus echo makes a PHP API endpoint.
  • Nested arrays encode and decode without extra work.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground