PHP JSON
last modified November 14, 2026
In this article, we show how to work with JSON in PHP. We use the
json_encode and json_decode functions, handle errors,
and produce and consume JSON in plain PHP, Symfony, Slim, and Laravel. The
examples were tested with PHP 8.5.
JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange
format. It is easily read and written by humans and parsed and generated by
machines. The application/json is the official Internet media type
for JSON. The JSON filename extension is .json.
JSON has six data types: object, array, string, number, boolean and null. The
json_encode function returns the JSON representation of the given
value. The json_decode function takes a JSON encoded string and
converts it into a PHP value.
PHP frameworks such as Symfony and Laravel have built-in methods that work with JSON.
PHP JSON encode
In the following example, we use the json_encode function.
<?php
declare(strict_types=1);
$words = ['falcon', 'sky', 'cloud', 'orange', 'wood', 'forest'];
echo json_encode($words), "\n";
$user = [
'name' => 'John Doe',
'age' => 34,
'married' => false,
'salary' => 2543.50,
'email' => null,
'languages' => ['English', 'Slovak'],
'address' => ['city' => 'Bratislava', 'street' => 'Kvetná'],
];
echo json_encode($user), "\n";
echo json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), "\n";
echo json_encode([1 => 'a', 2 => 'b']), "\n";
echo json_encode([]), "\n";
echo json_encode(new stdClass), "\n";
echo json_encode("a/b \"quoted\" ž"), "\n";
The example transforms PHP values into JSON strings. A list array (with
sequential keys starting from zero) becomes a JSON array; an associative array
becomes a JSON object. PHP null, booleans, integers and floats map to
their JSON counterparts.
echo json_encode($user, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE), "\n";
Flags change the output. JSON_PRETTY_PRINT adds whitespace and
indentation; JSON_UNESCAPED_UNICODE writes characters such as
á as they are instead of the \u00e1 escape sequence. A related flag,
JSON_UNESCAPED_SLASHES, keeps the forward slashes unescaped.
Note the last lines: an array whose keys do not start at zero becomes an object,
an empty array becomes [] and not {}; to get an empty
JSON object, we encode an empty stdClass object. Without
JSON_UNESCAPED_SLASHES, the slash in a string is escaped as
\/.
$ php encode.php
["falcon","sky","cloud","orange","wood","forest"]
{"name":"John Doe","age":34,"married":false,"salary":2543.5,"email":null,"languages":["English","Slovak"],"address":{"city":"Bratislava","street":"Kvetn\u00e1"}}
{
"name": "John Doe",
"age": 34,
"married": false,
"salary": 2543.5,
"email": null,
"languages": [
"English",
"Slovak"
],
"address": {
"city": "Bratislava",
"street": "Kvetná"
}
}
{"1":"a","2":"b"}
[]
{}
"a\/b \"quoted\" \u017e"
PHP JSON response
A web script that returns JSON should tell the client what it is sending by
setting the Content-Type header.
<?php
declare(strict_types=1);
$data = ['falcon', 'sky', 'cloud', 'orange', 'wood', 'forest'];
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_THROW_ON_ERROR);
The example sends a list of words as JSON. The JSON_THROW_ON_ERROR
flag makes json_encode throw an exception instead of returning
false when the value cannot be encoded.
$ php -S localhost:8000 json_response.php
We start the server and open localhost:8000 in a browser.
Modern web browsers show a JSON view for JSON data when they receive an appropriate content type in the header of the response. With curl, we see the header and the body.
$ curl -i localhost:8000 HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 ["falcon","sky","cloud","orange","wood","forest"]
PHP JSON decode
In the following example, we use the json_decode function.
<?php
declare(strict_types=1);
$data = '{
"name": "John Doe",
"occupation": "gardener",
"skills": ["planting", "pruning"],
"address": {"city": "Bratislava", "zip": "81101"}
}';
$a = json_decode($data, true);
echo "{$a['name']} is a {$a['occupation']}\n";
echo $a['skills'][1], "\n";
echo $a['address']['city'], "\n";
$o = json_decode($data);
echo "{$o->name} is a {$o->occupation}\n";
echo $o->address->city, "\n";
echo get_class($o), "\n";
The example transforms a JSON string into PHP values in two ways. By default,
json_decode turns a JSON object into a stdClass
object, which we read with the -> operator. When the second
argument is true, JSON objects become associative arrays, which
we read with square brackets. Nested objects and arrays are converted
recursively.
We recommend arrays when keys are dynamic or when the data is passed around the application; objects are convenient for reading fixed structures.
$ php decode.php John Doe is a gardener pruning Bratislava John Doe is a gardener Bratislava stdClass
PHP JSON types and big numbers
JSON and PHP have different type systems; the conversion has a few corner cases.
<?php
declare(strict_types=1);
$json = '{"id": 12345678901234567890, "price": 19.90, "tags": [], "empty": {}}';
var_dump(json_decode($json, true));
var_dump(json_decode($json, true, 512, JSON_BIGINT_AS_STRING)['id']);
echo json_encode(19.90), "\n";
echo json_encode(10.0), "\n";
echo json_encode(10.0, JSON_PRESERVE_ZERO_FRACTION), "\n";
echo json_encode('123'), ' ', json_encode('123', JSON_NUMERIC_CHECK), "\n";
echo json_encode(json_decode('{"empty": {}, "list": []}', true)), "\n";
echo json_encode(json_decode('{"empty": {}, "list": []}')), "\n";
An integer that is too large for a PHP int is decoded as a
float and loses precision; the JSON_BIGINT_AS_STRING
flag keeps it as a string. When encoding, 10.0 is written as
10 unless JSON_PRESERVE_ZERO_FRACTION is set, and the
JSON_NUMERIC_CHECK flag turns numeric strings into numbers, which is
rarely wanted.
The last two lines show the biggest trap: an empty JSON object {}
decoded into an array becomes [] when it is encoded back. Decoding
to objects keeps the difference.
$ php typed_decode.php
array(4) {
["id"]=>
float(1.2345678901234567E+19)
["price"]=>
float(19.9)
["tags"]=>
array(0) {
}
["empty"]=>
array(0) {
}
}
string(20) "12345678901234567890"
19.9
10
10.0
"123" 123
{"empty":[],"list":[]}
{"empty":{},"list":[]}
PHP JSON error handling
By default, json_decode returns null on invalid input,
which cannot be distinguished from a valid JSON null without
asking for the error code.
<?php
declare(strict_types=1);
$bad = '{"name": "John", }';
var_dump(json_decode($bad));
echo json_last_error(), ': ', json_last_error_msg(), "\n";
try {
json_decode($bad, false, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo get_class($e), ': ', $e->getMessage(), "\n";
}
try {
echo json_encode("bad \xB1\x31 utf8", JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo $e->getMessage(), "\n";
}
echo json_encode("bad \xB1\x31 utf8", JSON_INVALID_UTF8_SUBSTITUTE), "\n";
echo json_encode(['pi' => NAN] , JSON_PARTIAL_OUTPUT_ON_ERROR), "\n";
var_dump(json_validate('{"a": 1}'));
var_dump(json_validate('{a: 1}'));
The example shows the options. The json_last_error and
json_last_error_msg functions describe the last problem. The much
better approach is the JSON_THROW_ON_ERROR flag, which throws a
JsonException that we can catch.
The same flag works with json_encode; the example fails on a string
that is not valid UTF-8. We can also choose to substitute invalid characters with
JSON_INVALID_UTF8_SUBSTITUTE or to skip the problematic values
with JSON_PARTIAL_OUTPUT_ON_ERROR. The last two calls use
json_validate, which was added in PHP 8.3; it checks the syntax
without building the data structure, so it is cheap for large payloads.
$ php errors.php
NULL
4: Syntax error
JsonException: Syntax error
Malformed UTF-8 characters, possibly incorrectly encoded
"bad \ufffd1 utf8"
{"pi":0}
bool(true)
bool(false)
PHP JsonSerializable
Objects are encoded with their public properties. A class can take control
of the output by implementing the JsonSerializable interface.
<?php
declare(strict_types=1);
class Point
{
public function __construct(
public int $x,
public int $y,
private string $secret = 'hidden',
) {
}
}
class User implements JsonSerializable
{
public function __construct(
private string $name,
private string $email,
private string $passwordHash,
private DateTimeImmutable $created,
) {
}
public function jsonSerialize(): array
{
return [
'name' => $this->name,
'email' => $this->email,
'created' => $this->created->format(DATE_ATOM),
];
}
}
enum Status: string
{
case Active = 'active';
case Blocked = 'blocked';
}
echo json_encode(new Point(3, 4)), "\n";
$user = new User('John Doe', 'john@example.com', 'x1y2z3', new DateTimeImmutable('2026-01-15 10:30:00'));
echo json_encode($user, JSON_PRETTY_PRINT), "\n";
echo json_encode(['status' => Status::Active, 'all' => Status::cases()]), "\n";
The Point object is encoded with its public properties only; the
private $secret is skipped. The User class implements
jsonSerialize, which returns the data to encode. It leaves out the
password hash and formats the date. Backed enums are encoded as their value.
Implementing JsonSerializable keeps the decision of what is public in
the class itself, so that sensitive properties do not leak into an API
response by accident.
$ php serializable.php
{"x":3,"y":4}
{
"name": "John Doe",
"email": "john@example.com",
"created": "2026-01-15T10:30:00+00:00"
}
{"status":"active","all":["active","blocked"]}
PHP JSON read from file
In the following example, we read JSON data from a file.
[
{"name": "John Doe", "occupation": "gardener", "country": "USA"},
{"name": "Richard Roe", "occupation": "driver", "country": "UK"},
{"name": "Sibel Schumacher", "occupation": "architect", "country": "Germany"},
{"name": "Manuella Navarro", "occupation": "teacher", "country": "Spain"},
{"name": "Thomas Dawn", "occupation": "teacher", "country": "New Zealand"},
{"name": "Morris Holmes", "occupation": "programmer", "country": "Ireland"}
]
This is the JSON data. It is an array of objects.
<?php
declare(strict_types=1);
$data = file_get_contents(__DIR__ . '/data.json');
$users = json_decode($data, false, 512, JSON_THROW_ON_ERROR);
$counts = [];
foreach ($users as $user) {
printf("%-18s %-11s %s\n", $user->name, $user->occupation, $user->country);
$counts[$user->occupation] = ($counts[$user->occupation] ?? 0) + 1;
}
echo "\n";
arsort($counts);
echo json_encode($counts), "\n";
In the code example, we read the file with file_get_contents and
decode it with json_decode. We print each user with
printf and count the users by occupation. Finally, we sort the
counts with arsort and print them as JSON.
$ php read_json_file.php
John Doe gardener USA
Richard Roe driver UK
Sibel Schumacher architect Germany
Manuella Navarro teacher Spain
Thomas Dawn teacher New Zealand
Morris Holmes programmer Ireland
{"teacher":2,"gardener":1,"driver":1,"architect":1,"programmer":1}
PHP JSON data in an HTML table
In the next example, we place the data from the file into an HTML table.
<?php
declare(strict_types=1);
$data = file_get_contents(__DIR__ . '/data.json');
$users = json_decode($data, false, 512, JSON_THROW_ON_ERROR);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Users</title>
</head>
<body>
<table>
<tbody>
<tr>
<th>Name</th>
<th>Occupation</th>
<th>Country</th>
</tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?= htmlspecialchars($user->name) ?></td>
<td><?= htmlspecialchars($user->occupation) ?></td>
<td><?= htmlspecialchars($user->country) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
We decode the data at the top of the script and then use the
foreach loop in the template part. Every value is escaped with
htmlspecialchars before it is written into the page. When the file
is served with php -S localhost:8000, the page
/users_table.php displays a table with six rows.
PHP JSON SQLite database
In the following examples, we read data from an SQLite database and return it in JSON. First, we create the database.
BEGIN TRANSACTION;
DROP TABLE IF EXISTS cities;
CREATE TABLE cities(id INTEGER PRIMARY KEY, name TEXT, population INTEGER);
INSERT INTO cities(name, population) VALUES('Bratislava', 432000);
INSERT INTO cities(name, population) VALUES('Budapest', 1759000);
INSERT INTO cities(name, population) VALUES('Prague', 1280000);
INSERT INTO cities(name, population) VALUES('Warsaw', 1748000);
INSERT INTO cities(name, population) VALUES('Los Angeles', 3971000);
INSERT INTO cities(name, population) VALUES('New York', 8550000);
INSERT INTO cities(name, population) VALUES('Edinburgh', 464000);
INSERT INTO cities(name, population) VALUES('Berlin', 3671000);
COMMIT;
This SQL code creates a cities table in SQLite. With the
sqlite3 command line tool, we generate the database file and
list the rows of the new table.
$ sqlite3 test.db < cities.sql $ sqlite3 test.db "SELECT * FROM cities" 1|Bratislava|432000 2|Budapest|1759000 3|Prague|1280000 4|Warsaw|1748000 5|Los Angeles|3971000 6|New York|8550000 7|Edinburgh|464000 8|Berlin|3671000
PHP JSON read from database
We read the rows from the cities table and return them as JSON.
<?php
declare(strict_types=1);
$pdo = new PDO('sqlite:' . __DIR__ . '/test.db');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cities = $pdo->query('SELECT id, name, population FROM cities')
->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['cities' => $cities], JSON_THROW_ON_ERROR);
In the example, we retrieve the data from the database with PDO and return it as
JSON. The FETCH_ASSOC mode gives one associative array per row, so
that the rows are encoded as JSON objects. The integer columns of SQLite are
returned as PHP integers, so the numbers in the JSON are numbers.
$ php -S localhost:8000
We start the server in the directory with the scripts and the database.
We fetch the data with curl. The jq tool prints the first three
cities, one per line; the whole response is a single JSON line.
$ curl -s localhost:8000/fetch_all.php | jq -c ".cities[:3][]"
{"id":1,"name":"Bratislava","population":432000}
{"id":2,"name":"Budapest","population":1759000}
{"id":3,"name":"Prague","population":1280000}
PHP JSON and JS fetch API
In the following example, we use the JavaScript fetch API to get the
JSON data from a PHP script. The JSON data is stored in the data.json
file shown earlier.
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
readfile(__DIR__ . '/data.json');
We send the file to the client with readfile, with the right
content type.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Users</title>
<style>
table, th, td {
font: 15px 'Segoe UI', sans-serif;
border: solid 1px #ddd;
border-collapse: collapse;
padding: 2px 6px;
text-align: center;
}
tr:nth-child(odd) { background: #efefef; }
</style>
</head>
<body>
<button id="getData">Get data</button>
<p id="status"></p>
<div id="output"></div>
<script>
const button = document.getElementById('getData');
const output = document.getElementById('output');
const status = document.getElementById('status');
button.addEventListener('click', async () => {
status.textContent = 'Loading...';
try {
const res = await fetch('/data.php');
if (!res.ok) {
throw new Error(`HTTP error ${res.status}`);
}
const users = await res.json();
output.replaceChildren(createTable(users));
status.textContent = `${users.length} users loaded`;
} catch (err) {
status.textContent = `Error: ${err.message}`;
}
});
function createTable(users) {
const table = document.createElement('table');
const header = table.insertRow();
for (const title of ['Name', 'Occupation', 'Country']) {
const th = document.createElement('th');
th.textContent = title;
header.appendChild(th);
}
for (const user of users) {
const row = table.insertRow();
for (const value of Object.values(user)) {
row.insertCell().textContent = value;
}
}
return table;
}
</script>
</body>
</html>
We have a button in the document. When we click on the button, the
fetch function retrieves JSON data from the data.php
script. An HTML table is dynamically built and filled with the data. The
values are inserted with textContent, not innerHTML, so
that data containing HTML characters cannot inject markup into the page.
The picture shows the table after we have clicked on the button. The page is
served by the same built-in server (php -S localhost:8000) as the
script, so that fetch('/data.php') is a same-origin request. We can also
call the script directly with curl and check the response header.
$ curl -si localhost:8000/data.php | grep -i -E "^HTTP|content-type"
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
$ curl -s localhost:8000/data.php | jq -c '.[0]'
{"name":"John Doe","occupation":"gardener","country":"USA"}
PHP receive JSON
A client can also send JSON to the server. PHP does not fill $_POST
for the application/json content type, so we read the raw request body
from php://input.
<?php
declare(strict_types=1);
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
exit;
}
try {
$data = json_decode(file_get_contents('php://input'), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException) {
http_response_code(400);
header('Content-Type: application/json');
echo json_encode(['error' => 'Invalid JSON']);
exit;
}
$name = $data['name'] ?? 'guest';
$message = $data['message'] ?? 'hello there';
header('Content-Type: application/json; charset=utf-8');
echo json_encode(['greeting' => "$name says: $message"]);
The script accepts only POST requests, decodes the body with
JSON_THROW_ON_ERROR, and answers with a JSON object. When the body is not
valid JSON, we respond with the status code 400 and an error message. The empty
parameter list in catch (JsonException) is allowed since PHP 8.0 when we do
not need the exception object.
$ php -S localhost:8000
We start the server. The two curl commands send a valid and an invalid body.
$ curl -s -H "Content-Type: application/json" -d '{"name":"Lucia","message":"Cau"}' localhost:8000/greet.php
{"greeting":"Lucia says: Cau"}
$ curl -si -d '{bad' localhost:8000/greet.php | grep -E "^HTTP|error"
HTTP/1.1 400 Bad Request
{"error":"Invalid JSON"}
PHP JSON from client
Symfony provides the HttpClient component which enables us to
create HTTP requests in PHP. We can also send and receive JSON.
$ composer require symfony/http-client
We install the symfony/http-client component.
<?php
declare(strict_types=1);
require __DIR__ . '/vendor/autoload.php';
use Symfony\Component\HttpClient\HttpClient;
$url = $argv[1] ?? 'http://localhost:8000/greet.php';
$client = HttpClient::create();
$response = $client->request('POST', $url, [
'json' => [
'name' => 'Lucia',
'message' => 'Cau',
],
]);
echo $response->getStatusCode(), ' ', $response->getHeaders()['content-type'][0], "\n";
$data = $response->toArray();
echo $data['greeting'], "\n";
The example sends a POST request with a JSON payload. The json
option encodes the array and sets the Content-Type header to
application/json for us. The toArray method decodes the
response and throws an exception if it is not valid JSON. The URL is taken from
the command line, so that we can use the script against the other servers in this
article.
We run it against the greet.php server from the previous section.
The first output line is the status code and the content type.
$ php send_json_req.php 200 application/json; charset=utf-8 Lucia says: Cau
PHP JSON in Slim
In the following example, we return JSON data from a Slim application.
$ composer require slim/slim slim/psr7
We install the slim/slim framework and the slim/psr7
implementation of PSR-7.
<?php
declare(strict_types=1);
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();
$app->addErrorMiddleware(true, true, true);
function json(Response $response, mixed $data, int $status = 200): Response
{
$response->getBody()->write(json_encode($data, JSON_THROW_ON_ERROR));
return $response
->withHeader('Content-Type', 'application/json')
->withStatus($status);
}
$cities = [
['id' => 1, 'name' => 'Bratislava', 'population' => 432000],
['id' => 2, 'name' => 'Budapest', 'population' => 1759000],
['id' => 3, 'name' => 'Prague', 'population' => 1280000],
['id' => 4, 'name' => 'Warsaw', 'population' => 1748000],
['id' => 5, 'name' => 'Los Angeles', 'population' => 3971000],
['id' => 6, 'name' => 'New York', 'population' => 8550000],
['id' => 7, 'name' => 'Edinburgh', 'population' => 464000],
['id' => 8, 'name' => 'Berlin', 'population' => 3671000],
];
$app->get('/city', function (Request $request, Response $response) use ($cities): Response {
return json($response, ['cities' => $cities]);
});
$app->get('/city/{id}', function (Request $request, Response $response, array $args) use ($cities): Response {
foreach ($cities as $city) {
if ($city['id'] === (int) $args['id']) {
return json($response, $city);
}
}
return json($response, ['error' => 'City not found'], 404);
});
$app->post('/greet', function (Request $request, Response $response): Response {
$data = (array) $request->getParsedBody();
$name = $data['name'] ?? 'guest';
$message = $data['message'] ?? 'hello there';
return json($response, ['greeting' => "$name says: $message"]);
});
$app->run();
Slim 4 has no JSON helper of its own, so we write a small json function that
encodes the data, writes it to the response body and sets the
Content-Type header and the status code. The
/city route returns all cities, /city/{id} one city or
a 404 response, and the /greet route reads a JSON body. The body is
decoded by the middleware added with addBodyParsingMiddleware.
$ php -S localhost:8000 -t public
We start the server.
We test it with curl and with the Symfony HttpClient script from the previous section.
$ curl localhost:8000/city | jq -c '.cities[:3][]'
{"id":1,"name":"Bratislava","population":432000}
{"id":2,"name":"Budapest","population":1759000}
{"id":3,"name":"Prague","population":1280000}
$ curl localhost:8000/city/3
{"id":3,"name":"Prague","population":1280000}
$ curl -si localhost:8000/city/99 | grep -E '^HTTP|error'
HTTP/1.1 404 Not Found
{"error":"City not found"}
$ curl -s -H 'Content-Type: application/json' -d '{"name":"Lucia","message":"Cau"}' localhost:8000/greet
{"greeting":"Lucia says: Cau"}
$ php send_json_req.php http://localhost:8000/greet
200 application/json
Lucia says: Cau
PHP JSON in Symfony
In the following example, we send a JSON response from a Symfony application.
$ composer create-project symfony/skeleton symjson $ cd symjson $ sqlite3 var/cities.db < cities.sql
A new application is created with the Symfony skeleton, and the SQLite database is
created from the cities.sql file shown earlier. Symfony 8 requires
PHP 8.4 or newer.
<?php
declare(strict_types=1);
namespace App\Repository;
use PDO;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
class CityRepository
{
private PDO $pdo;
public function __construct(#[Autowire('%kernel.project_dir%/var/cities.db')] string $dbFile)
{
$this->pdo = new PDO('sqlite:' . $dbFile);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function all(): array
{
return $this->pdo->query('SELECT id, name, population FROM cities')
->fetchAll(PDO::FETCH_ASSOC);
}
public function find(int $id): ?array
{
$stmt = $this->pdo->prepare('SELECT id, name, population FROM cities WHERE id = ?');
$stmt->execute([$id]);
return $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}
}
In the CityRepository, we have the all and
find methods, which use PDO to read the rows. The path to the database
file is injected with the #[Autowire] attribute from the
kernel.project_dir parameter. The repository is registered as a
service automatically.
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Repository\CityRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
class CityController extends AbstractController
{
#[Route('/city', name: 'city_list', methods: ['GET'])]
public function list(CityRepository $repository): JsonResponse
{
return $this->json(['cities' => $repository->all()]);
}
#[Route('/city/{id<\d+>}', name: 'city_show', methods: ['GET'])]
public function show(int $id, CityRepository $repository): JsonResponse
{
$city = $repository->find($id);
if ($city === null) {
return $this->json(['error' => 'City not found'], 404);
}
return $this->json($city);
}
}
Inside the controller, we fetch the data using the CityRepository. The
data is transformed into JSON with the json helper of the
AbstractController, which returns a JsonResponse with the
right content type. The {id<\d+>} route placeholder accepts only digits,
and the controller argument is converted to int.
<?php
declare(strict_types=1);
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;
class GreetController extends AbstractController
{
#[Route('/greet', name: 'greet', methods: ['POST'])]
public function greet(Request $request): JsonResponse
{
$data = $request->getPayload();
$name = $data->get('name', 'guest');
$message = $data->get('message', 'hello there');
return $this->json(['greeting' => "$name says: $message"]);
}
}
The GreetController processes JSON data. The getPayload
method of the request returns the decoded body of a JSON request (and the
form data of other requests). Invalid JSON is rejected by Symfony with the status
code 400.
$ php -S localhost:8000 -t public
We start the web server. The symfony serve command of the Symfony CLI can
be used instead.
We test the three routes and run the client script.
$ curl localhost:8000/city | jq -c '.cities[:3][]'
{"id":1,"name":"Bratislava","population":432000}
{"id":2,"name":"Budapest","population":1759000}
{"id":3,"name":"Prague","population":1280000}
$ curl localhost:8000/city/3
{"id":3,"name":"Prague","population":1280000}
$ curl -si localhost:8000/city/99 | grep -E '^HTTP|error'
HTTP/1.1 404 Not Found
{"error":"City not found"}
$ curl -s -H 'Content-Type: application/json' -d '{"name":"Lucia","message":"Cau"}' localhost:8000/greet
{"greeting":"Lucia says: Cau"}
$ php send_json_req.php http://localhost:8000/greet
200 application/json
Lucia says: Cau
PHP JSON in Laravel
In the following example, we send a JSON response from a Laravel application.
$ composer create-project laravel/laravel larajson $ cd larajson
We create a new Laravel application. The generated .env file is
already configured to use an SQLite database stored in
database/database.sqlite, so we do not need to configure anything.
$ php artisan make:migration create_cities_table $ php artisan make:seeder CitySeeder
We create a migration for the cities table and a data seeder for our database.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('cities', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->integer('population');
});
}
public function down(): void
{
Schema::dropIfExists('cities');
}
};
In the migration file, we create a schema for the cities table. The
file name starts with the time stamp of its creation, so yours will differ.
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class CitySeeder extends Seeder
{
public function run(): void
{
DB::table('cities')->insert([
['name' => 'Bratislava', 'population' => 432000],
['name' => 'Budapest', 'population' => 1759000],
['name' => 'Prague', 'population' => 1280000],
['name' => 'Warsaw', 'population' => 1748000],
['name' => 'Los Angeles', 'population' => 3971000],
['name' => 'New York', 'population' => 8550000],
['name' => 'Edinburgh', 'population' => 464000],
['name' => 'Berlin', 'population' => 3671000],
]);
}
}
The seeder inserts eight rows into the table. We run the migrations and execute the seeder with two commands.
$ php artisan migrate INFO Running migrations. 2026_11_14_175747_create_cities_table .. 13.89ms DONE $ php artisan db:seed --class=CitySeeder INFO Seeding database. Database\Seeders\CitySeeder .. RUNNING Database\Seeders\CitySeeder .. 18 ms DONE
<?php
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
Route::get('/city', function (): JsonResponse {
$cities = DB::table('cities')->get();
return response()->json(['cities' => $cities]);
});
Route::get('/city/{id}', function (int $id): JsonResponse {
$city = DB::table('cities')->find($id);
if ($city === null) {
return response()->json(['error' => 'City not found'], 404);
}
return response()->json($city);
})->whereNumber('id');
Route::post('/greet', function (Request $request): JsonResponse {
$name = $request->input('name', 'guest');
$message = $request->input('message', 'hello there');
return response()->json(['greeting' => "$name says: $message"]);
});
Inside the routes, we select data from the database with the query builder and return
it as JSON with the json helper of the response function.
The whereNumber constraint restricts the id parameter to digits. A route
that returns an array or a collection would be converted to JSON automatically, but
the explicit helper makes the intent clear and allows us to set the status code.
<?php
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->validateCsrfTokens(except: ['greet']);
})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen(
fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
);
})->create();
Routes in routes/web.php are protected against cross-site request
forgery, so a POST request without a token is rejected with the status code 419. We
exempt the /greet route in the middleware configuration, so that
a non-browser client can use it. Real API endpoints should rather go to
routes/api.php, which is created with php artisan install:api
and uses token authentication.
$ php artisan serve
We run the web server.
We get the data with the curl tool and send a JSON request with the
client script.
$ curl localhost:8000/city | jq -c '.cities[:3][]'
{"id":1,"name":"Bratislava","population":432000}
{"id":2,"name":"Budapest","population":1759000}
{"id":3,"name":"Prague","population":1280000}
$ curl localhost:8000/city/3
{"id":3,"name":"Prague","population":1280000}
$ curl -si localhost:8000/city/99 | grep -E '^HTTP|error'
HTTP/1.1 404 Not Found
{"error":"City not found"}
$ curl -s -H 'Content-Type: application/json' -d '{"name":"Lucia","message":"Cau"}' localhost:8000/greet
{"greeting":"Lucia says: Cau"}
$ php send_json_req.php http://localhost:8000/greet
200 application/json
Lucia says: Cau
Source
In this article, we have worked with JSON data in plain PHP, Symfony, Slim, and
Laravel. We have encoded, decoded and validated JSON, handled errors, customized the
output with JsonSerializable, and sent JSON with the Symfony
HttpClient. See also the PHP GET/POST request,
PHP PDO and PHP SQLite
tutorials.
Author
List all PHP tutorials.