Question

Pretty-Printing JSON in PHP with json_encode

phpjsonpretty-print

Question

I am building a PHP script that sends JSON data to another script. The script collects data in a large associative array and outputs it using json_encode().

For example:

<?php
$data = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'catnip'
);

header('Content-Type: application/json');
echo json_encode($data);

This produces compact JSON like this:

{"a":"apple","b":"banana","c":"catnip"}

That works, but for readability I would prefer formatted output like this:

{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}

Is there a built-in way to pretty-print JSON in PHP without using a manual string-formatting workaround?

Short Answer

By the end of this page, you will understand how to generate human-readable JSON in PHP, when to use pretty-printed output, how json_encode() options work, and how developers handle JSON formatting in real applications and APIs.

Concept

JSON can be output in two common styles:

  • Compact JSON: everything is on one line with no extra spaces
  • Pretty-printed JSON: includes indentation and line breaks for readability

In PHP, JSON is usually created with json_encode(). By default, PHP returns compact JSON because it is smaller and efficient for machines to read. However, when developers need to inspect API responses, debug payloads, save readable files, or log structured data, pretty-printed JSON is much easier to work with.

The key idea is that the data stays the same. Only the formatting of the output string changes.

PHP provides this formatting through the JSON_PRETTY_PRINT option in json_encode().

Example:

json_encode($data, JSON_PRETTY_PRINT);

This tells PHP to insert whitespace, indentation, and line breaks into the JSON output.

Why this matters:

  • It improves debugging
  • It makes saved JSON files easier to inspect
  • It helps developers compare output in version control
  • It makes API examples easier to read in documentation

It does not change the meaning of the JSON. A parser reads compact and pretty JSON the same way.

Mental Model

Think of JSON like a paragraph of text.

  • Compact JSON is like writing everything in one long sentence with no paragraph breaks.
  • Pretty-printed JSON is like using line breaks and indentation so a person can scan it quickly.

The words have not changed. Only the presentation has changed.

So JSON_PRETTY_PRINT is like telling PHP: "Write this neatly so humans can read it more easily."

Take Quiz

Syntax and Examples

Basic syntax

json_encode($value, JSON_PRETTY_PRINT);

The second argument is a bitmask of options that changes how JSON is produced.

Simple example

<?php
$data = array(
    'a' => 'apple',
    'b' => 'banana',
    'c' => 'catnip'
);

header('Content-Type: application/json');
echo json_encode($data, JSON_PRETTY_PRINT);

Output:

{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}

Using multiple options together

You can combine JSON options with the bitwise OR operator |.

<?php
$data = array(
    'name' => 'Alice',
    'message' => 'Hello',
    'path' => 'C:\\temp'
);

echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

This is useful when you want readable formatting and also want to avoid escaping some characters unnecessarily.

Example with nested data

<?php
$data = array(
    'user' => array(
        'name' => 'Sam',
        'age' => 28
    ),
    'roles' => array('admin', 'editor')
);

echo json_encode($data, JSON_PRETTY_PRINT);

Output:

{
    "user": {
        "name": "Sam",
        "age": 28
    },
    "roles": [
        "admin",
        "editor"
    ]
}

The indentation makes nested arrays and objects much easier to understand.

Step by Step Execution

Consider this code:

<?php
$data = array(
    'fruit' => 'apple',
    'count' => 3,
    'colors' => array('red', 'green')
);

$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;

Here is what happens step by step:

  1. PHP creates an associative array called $data.
  2. The key 'fruit' maps to the string 'apple'.
  3. The key 'count' maps to the number 3.
  4. The key 'colors' maps to another array containing 'red' and 'green'.
  5. json_encode($data, JSON_PRETTY_PRINT) converts the PHP array into a JSON string.
  6. Because JSON_PRETTY_PRINT is passed, PHP adds line breaks and indentation.
  7. The formatted JSON string is stored in $json.
  8. echo $json; prints the result.

Output:

{
    "fruit": "apple",
    "count": 3,
    "colors": [
        "red",
        "green"
    ]
}

Notice that:

  • PHP associative arrays become JSON objects
  • PHP indexed arrays become JSON arrays
  • numbers stay numbers
  • strings stay strings

Real World Use Cases

Pretty-printed JSON is commonly used in situations where humans need to inspect the output.

API debugging

When testing an API response in a browser or tool, formatted JSON is much easier to read.

Log files

Applications often log structured data as JSON. Pretty formatting helps developers inspect logs during debugging.

Configuration export

If a PHP app exports configuration or report data as JSON files, readable formatting makes manual review easier.

Documentation examples

When showing sample API responses in docs, pretty JSON is clearer for learners and developers.

Local development tools

During development, many teams output pretty JSON in dev mode but compact JSON in production.

Take Quiz

Real Codebase Usage

In real projects, developers often use pretty-printing selectively rather than everywhere.

Common pattern: pretty print in development

<?php
$options = 0;

if ($isDebug) {
    $options |= JSON_PRETTY_PRINT;
}

echo json_encode($data, $options);

This keeps production responses smaller while making local debugging easier.

Common pattern: validate encoding success

<?php
$json = json_encode($data, JSON_PRETTY_PRINT);

if ($json === false) {
    error_log(json_last_error_msg());
} else {
    echo $json;
}

This prevents silent failures when invalid data is passed.

Common pattern: writing readable JSON files

<?php
file_put_contents('report.json', json_encode($data, JSON_PRETTY_PRINT));

This is useful for exports, cached files, and generated fixtures.

Common pattern: API response helper

In many codebases, JSON output is wrapped in a helper or framework response class so formatting rules are applied consistently.

<?php
function sendJson($data, $pretty = false) {
    header('Content-Type: application/json');
    $options = $pretty ? JSON_PRETTY_PRINT : 0;
    echo json_encode($data, $options);
}

This avoids repeating logic across the project.

Common Mistakes

1. Using the wrong content type

Broken example:

header('Content-Type: text/javascript');

Better:

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

application/json is the correct content type for JSON responses.

2. Thinking pretty-printing changes the data

Pretty-printing only changes whitespace. The JSON values and structure stay the same.

3. Forgetting to check for encoding errors

Broken example:

echo json_encode($data, JSON_PRETTY_PRINT);

Safer example:

$json = json_encode($data, JSON_PRETTY_PRINT);
if ($json === false) {
    echo json_last_error_msg();
}

4. Expecting older PHP versions to support JSON_PRETTY_PRINT

If you are working in an older environment, this option may not exist. Always confirm the PHP version in legacy projects.

5. Confusing PHP arrays with JSON arrays

PHP associative arrays become JSON objects, not JSON arrays.

<?php
$data = array('a' => 'apple');
echo json_encode($data, JSON_PRETTY_PRINT);

Output:

{
    "a": "apple"
}

6. Pretty-printing large payloads unnecessarily

Readable output is helpful, but it adds extra bytes. For high-volume production APIs, compact JSON is often preferred.

Comparisons

Compact JSON vs pretty-printed JSON

StyleExampleBest forTrade-off
Compact JSON{"a":"apple"}APIs, smaller payloads, productionHarder for humans to read
Pretty-printed JSONMulti-line indented JSONDebugging, logs, docs, saved filesLarger output size

json_encode() without and with options

ApproachCodeResult
Defaultjson_encode($data)Compact JSON
Pretty printjson_encode($data, JSON_PRETTY_PRINT)Indented readable JSON
Multiple options`json_encode($data, JSON_PRETTY_PRINTJSON_UNESCAPED_SLASHES)`

Manual formatting vs built-in formatting

ApproachRecommendationWhy
Manual string replacementAvoid when possibleFragile and error-prone
JSON_PRETTY_PRINTPreferredBuilt-in, clear, reliable
Take Quiz

Cheat Sheet

json_encode($data); // compact JSON
json_encode($data, JSON_PRETTY_PRINT); // readable JSON
json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); // combine options

Rules to remember

  • Use json_encode() to convert PHP data to JSON
  • Use JSON_PRETTY_PRINT for indentation and line breaks
  • Use application/json as the response content type
  • Pretty-printing changes formatting, not data
  • Associative arrays become JSON objects
  • Indexed arrays become JSON arrays

Safe pattern

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

$json = json_encode($data, JSON_PRETTY_PRINT);

if ($json === false) {
    echo json_last_error_msg();
} else {
    echo $json;
}

Common related options

  • JSON_PRETTY_PRINT
  • JSON_UNESCAPED_SLASHES
  • JSON_UNESCAPED_UNICODE

Good default for readable output

json_encode($data, JSON_PRETTY_PRINT);

FAQ

How do I pretty-print JSON in PHP?

Use json_encode($data, JSON_PRETTY_PRINT).

Does pretty-printing make JSON invalid?

No. Extra whitespace is valid in JSON and ignored by parsers.

Should I use pretty-printed JSON in production APIs?

Usually only if readability matters. Compact JSON is smaller and more efficient.

What is the correct header for JSON in PHP?

Use:

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

Can I combine JSON_PRETTY_PRINT with other options?

Yes. Use the | operator, for example:

json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);

Why does my PHP array become a JSON object?

If the array is associative, PHP encodes it as a JSON object.

What if json_encode() fails?

Check whether the result is false and inspect json_last_error_msg().

Is manual JSON formatting a good idea?

Usually no. Built-in JSON options are safer and easier to maintain.

Take Quiz

Mini Project

Description

Build a small PHP script that returns a readable JSON response for a product catalog. This demonstrates how to create structured PHP arrays, encode them as JSON, and output pretty-printed data that is easy to inspect during development.

Goal

Create a PHP endpoint that outputs a pretty-printed JSON catalog of products with the correct content type.

Requirements

  1. Create a PHP array containing at least three products.
  2. Each product should have a name, price, and inStock field.
  3. Output the data as JSON using the correct HTTP content type.
  4. Use pretty-printing so the response is easy to read.
  5. Check whether JSON encoding succeeds before echoing the result.
Take Quiz

Keep learning

Related questions

View more