Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to send a JSON response

Short answer

Send the type header and print the result of json_encode():

<?php
 
header('Content-Type: application/json; charset=utf-8');
 
echo json_encode(['id' => 1, 'title' => 'Tea'], JSON_UNESCAPED_UNICODE);

An error response

Set the status code before printing:

<?php
 
http_response_code(404);
header('Content-Type: application/json; charset=utf-8');
 
echo json_encode(['error' => 'Not found']);

What the client receives

The JSON string looks like this:

<?php
 
echo json_encode(['id' => 1, 'tags' => ['php', 'sql'], 'active' => true]);

Output:

{"id":1,"tags":["php","sql"],"active":true}

Functions used in this recipe

  • json_encode — Converts a value to a JSON string.
  • header — Sends an HTTP response header.

Thanks for reading!

Donate to the site — we work hard for you.