PHP Tutorial · PHP for the Web · Lesson 25 of 38
PHP JSON
Encode arrays and objects as JSON and decode JSON into PHP.
json_encode
Turns arrays and objects into a JSON string. Use flags for readable output:
<?php
$data = ["name" => "Ada", "skills" => ["php", "sql"], "active" => true, "score" => null];
echo json_encode($data), "\n";
echo json_encode(["path" => "/api/users", "city" => "Zürich"], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), "\n";
echo json_encode([1, 2]), " vs ", json_encode([1 => "a", 2 => "b"]), "\n";
echo json_encode(["id" => 1, "tags" => ["a"]], JSON_PRETTY_PRINT), "\n";
Output
{"name":"Ada","skills":["php","sql"],"active":true,"score":null}
{"path":"/api/users","city":"Zürich"}
[1,2] vs {"1":"a","2":"b"}
{
"id": 1,
"tags": [
"a"
]
}json_decode
Pass true as the second argument to get associative arrays (otherwise you get stdClass objects). Use JSON_THROW_ON_ERROR so invalid JSON throws instead of silently returning null:
<?php
$json = '{"id": 7, "title": "Learn PHP", "tags": ["php", "web"]}';
$todo = json_decode($json, true);
echo $todo["title"], " #", $todo["tags"][0], "\n";
$obj = json_decode($json);
echo $obj->title, "\n";
try {
json_decode("{bad json}", true, flags: JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo "Invalid JSON: ", $e->getMessage(), "\n";
}
Output
Learn PHP #php Learn PHP Invalid JSON: Syntax error
A JSON API endpoint
<?php
header("Content-Type: application/json");
echo json_encode(["status" => "ok", "items" => $items]);
Test yourself
What second argument makes json_decode() return arrays instead of objects?
truefalseJSON_ARRAY1.0
Show answer
Answer: true