How to format a JSON response in PHP

On this page
  1. Creating an Array and Converting It to JSON
  2. Formatting JSON Responses from Objects
  3. Returning JSON as an HTTP Response
  4. JSON Error Handling
  5. Formatting JSON Output
  6. Additional JSON Encoding Options
  7. Processing JSON in Client Applications
  8. Practical Considerations
  9. Summary

JSON (JavaScript Object Notation) is a lightweight data format commonly used for exchanging information between applications, APIs, databases, and web services. Because it is both human-readable and easy for software to process, JSON has become a standard format for data communication on the web.

In PHP, JSON responses are typically generated using built-in functions that convert arrays and objects into JSON-formatted data.

Creating an Array and Converting It to JSON

One of the most common ways to generate a JSON response is to create an associative array and convert it using the json_encode() function.

Example:

$data = array(
    "name" => "John Doe",
    "age" => 30,
    "city" => "New York"
);

$jsonData = json_encode($data);

The $jsonData variable will contain the JSON representation of the array.

Result:

{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

Formatting JSON Responses from Objects

PHP objects can also be converted directly into JSON.

Example:

class Person {
    public $name;
    public $age;
    public $city;
}

$person = new Person();
$person->name = "Jane Smith";
$person->age = 35;
$person->city = "Los Angeles";

$jsonData = json_encode($person);

The resulting JSON structure will contain the object’s public properties.

Returning JSON as an HTTP Response

When building APIs or web services, it is important to send the correct content type header before returning JSON data.

Example:

header('Content-Type: application/json');

echo json_encode($data);

This tells the client application that the response contains JSON data rather than HTML or plain text.

JSON Error Handling

JSON generation can fail if the data contains invalid values or unsupported data types.

It is good practice to verify that json_encode() completed successfully.

Example:

$jsonData = json_encode($data);

if ($jsonData === false) {
    $jsonData = json_encode(array(
        "error" => "Error while generating JSON data."
    ));
}

Modern PHP versions also provide additional error handling functions.

Example:

$jsonData = json_encode($data);

if (json_last_error() !== JSON_ERROR_NONE) {
    echo json_last_error_msg();
}

This can help identify the reason a JSON operation failed.

Formatting JSON Output

By default, JSON output is generated as a compact string.

For debugging or development purposes, you can improve readability using the JSON_PRETTY_PRINT option.

Example:

$jsonData = json_encode($data, JSON_PRETTY_PRINT);

Output:

{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

This formatting is useful when reviewing API responses manually.

Additional JSON Encoding Options

The json_encode() function supports several options that can modify the output.

Common examples include:

Option Purpose
JSON_PRETTY_PRINT Formats JSON for readability
JSON_UNESCAPED_UNICODE Prevents Unicode characters from being escaped
JSON_UNESCAPED_SLASHES Prevents forward slashes from being escaped
JSON_NUMERIC_CHECK Converts numeric strings to numbers

Multiple options can be combined using the pipe (|) operator.

Example:

$jsonData = json_encode(
    $data,
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE
);

Processing JSON in Client Applications

Client applications can receive and process JSON data using built-in tools available in most programming languages.

In JavaScript, the JSON.parse() method converts a JSON string into an object.

Example:

var jsonData = '{"name":"John Doe","age":30,"city":"New York"}';

var obj = JSON.parse(jsonData);

console.log(obj.name);

Output:

John Doe

This allows client-side applications to access and use the data returned by PHP APIs.

Practical Considerations

When building APIs or applications that return JSON responses:

  • Always send the correct Content-Type header.
  • Validate data before encoding it.
  • Handle JSON errors appropriately.
  • Use readable formatting during development when necessary.
  • Return consistent response structures for easier integration.

Following these practices can help improve compatibility between systems and simplify troubleshooting.

Summary

JSON is a widely used format for exchanging data between applications and services. In PHP, JSON responses can be generated using the json_encode() function with arrays or objects.

By combining proper error handling, response headers, and formatting options, developers can create reliable and consistent JSON responses that integrate effectively with APIs, web applications, and external systems.

Didn't find an answer?

Our support team is here for you 24/7 – write to us and we will help you sort it out.