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."
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 |.
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:
- PHP creates an associative array called
$data. - The key
'fruit'maps to the string'apple'. - The key
'count'maps to the number3. - The key
'colors'maps to another array containing'red'and'green'. json_encode($data, JSON_PRETTY_PRINT)converts the PHP array into a JSON string.- Because
JSON_PRETTY_PRINTis passed, PHP adds line breaks and indentation. - The formatted JSON string is stored in .
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.
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(, JSON_PRETTY_PRINT));
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
Comparisons
Compact JSON vs pretty-printed JSON
| Style | Example | Best for | Trade-off |
|---|---|---|---|
| Compact JSON | {"a":"apple"} | APIs, smaller payloads, production | Harder for humans to read |
| Pretty-printed JSON | Multi-line indented JSON | Debugging, logs, docs, saved files | Larger output size |
json_encode() without and with options
| Approach | Code | Result |
|---|---|---|
| Default | json_encode($data) | Compact JSON |
| Pretty print |
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_PRINTfor indentation and line breaks - Use
application/jsonas 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
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?
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
- Create a PHP array containing at least three products.
- Each product should have a name, price, and inStock field.
- Output the data as JSON using the correct HTTP content type.
- Use pretty-printing so the response is easy to read.
- Check whether JSON encoding succeeds before echoing the result.
Keep learning
Related questions
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.