How to Send JSON Response in PHP: Simple Guide
To send a JSON response in PHP, use
header('Content-Type: application/json') to set the response type, then output your data with echo json_encode($data). This tells the browser to expect JSON and sends your PHP array or object as a JSON string.Syntax
To send JSON from PHP, you first set the HTTP header to tell the browser the content is JSON. Then you convert your PHP data to a JSON string and print it.
header('Content-Type: application/json'): Sets the response type to JSON.json_encode($data): Converts PHP arrays or objects to JSON format.echo: Sends the JSON string to the client.
php
<?php header('Content-Type: application/json'); $data = ['key' => 'value']; echo json_encode($data); ?>
Output
{"key":"value"}
Example
This example shows how to send a JSON response with a list of users. It sets the header, creates an array, converts it to JSON, and sends it.
php
<?php header('Content-Type: application/json'); $users = [ ['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob'], ['id' => 3, 'name' => 'Charlie'] ]; echo json_encode($users); ?>
Output
[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"},{"id":3,"name":"Charlie"}]
Common Pitfalls
Common mistakes when sending JSON in PHP include:
- Not setting the
Content-Typeheader, so the client doesn't know the response is JSON. - Outputting extra whitespace or HTML before the JSON, which breaks the JSON format.
- Trying to encode resources or unsupported data types, which causes
json_encodeto fail.
Always call header() before any output and check your data is JSON-serializable.
php
<?php // Wrong way: header after output // echo 'Hello'; // header('Content-Type: application/json'); // This will cause an error // Right way: header('Content-Type: application/json'); $data = ['success' => true]; echo json_encode($data); ?>
Output
{"success":true}
Quick Reference
| Step | Code | Purpose |
|---|---|---|
| 1 | header('Content-Type: application/json'); | Set response type to JSON |
| 2 | $data = [...]; | Prepare PHP data (array or object) |
| 3 | echo json_encode($data); | Convert and send JSON string |
Key Takeaways
Always set the Content-Type header to application/json before output.
Use json_encode() to convert PHP data to JSON format.
Avoid any output before setting headers to prevent errors.
Ensure your data contains only JSON-serializable types.
Test your JSON output to confirm it is valid and well-formed.