Skip to content

PHP Tutorial Working with JSON and APIs

What Is JSON?

Lesson 304 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

JSON (JavaScript Object Notation) is a plain-text format for sending and storing data. Despite the name, nearly every programming language can read and write it, and almost every web API uses it.

data.json
JSON
{
    "name": "Isha",
    "age": 29,
    "active": true,
    "skills": ["php", "sql"],
    "address": {
        "city": "Pune",
        "postcode": "411001"
    },
    "manager": null
}

Why JSON matters in PHP

  • A JavaScript front end asks your PHP code for data, and you answer in JSON.
  • A mobile app talks to your server with JSON.
  • You call other services (payments, maps, weather) and read their JSON replies.
  • You store settings or flexible data in a JSON file or column.

The syntax

JSON has only a few building blocks.

JSONExamplePHP equivalent
Object{"name": "Ana"}Associative array (or stdClass)
Array[1, 2, 3]Indexed array
String"hello"string
Number42, 3.14int or float
Booleantrue, falsebool
Nullnullnull

The rules (stricter than PHP)

  • Strings use double quotes only. 'single' is invalid.
  • Keys must be strings in double quotes.
  • No trailing commas, no comments.
  • No undefined, no functions, no dates (dates are written as strings).
index.php
PHP
<?php
var_dump(json_decode('{"name": "Ana"}', true));
var_dump(json_decode("{'name': 'Ana'}", true));   // single quotes: invalid
Output
OUTPUT
array(1) {
  ["name"]=>
  string(3) "Ana"
}
NULL

Reading and writing it

PHP has two main functions, covered in the next lessons.

index.php
PHP
<?php
$data = ["name" => "Ana", "skills" => ["php", "sql"]];

$json = json_encode($data);

echo $json . "\n";

$back = json_decode($json, true);

echo $back["skills"][1];
Output
OUTPUT
{"name":"Ana","skills":["php","sql"]}
sql

JSON vs XML vs CSV

FormatGood for
JSONAPIs, settings, nested data
XMLOlder systems, documents with a strict structure
CSVFlat tables, spreadsheet exchange

MIME type

When a server sends JSON, it sets the header Content-Type: application/json. See Building a JSON Response.

Pretty or compact

Both of these are the same data. APIs usually send the compact form to save bytes. A pretty form is for people.

info
Why this matters in WordPress and Laravel
The WordPress REST API (/wp-json/wp/v2/posts) and Laravel API routes both speak JSON. A WordPress block editor page talks to the server in JSON all the time.