JSON (JavaScript Object Notation) is the standard data exchange format for web APIs. PHP's json_encode() and json_decode() make it trivial to work with.
$user = [
"id" => 1,
"name" => "Alice",
"roles" => ["admin", "editor"],
"meta" => ["active" => true]
];
echo json_encode($user);
// {"id":1,"name":"Alice","roles":["admin","editor"],"meta":{"active":true}}
echo json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
$json = '{"id":1,"name":"Alice","active":true}';
// As associative array (recommended)
$data = json_decode($json, true);
echo $data["name"]; // Alice
// As object
$obj = json_decode($json);
echo $obj->name; // Alice
header("Content-Type: application/json; charset=utf-8");
echo json_encode([
"status" => "success",
"message" => "User created",
"data" => ["id" => 42, "name" => "Alice"]
]);
$data = json_decode($untrustedInput, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new InvalidArgumentException(
"Invalid JSON: " . json_last_error_msg()
);
}