PHP "pretty print" json_encode

PHP "pretty print" json_encode

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP "pretty print" json_encode

When generating JSON files for client consumption, readability often becomes a requirement rather than an afterthought. A minified string like {"product_name":"prod1","val1":1,"val2":8} is technically valid but difficult to parse visually. If you are working with PHP 5.2.x or modern versions, the solution is not to abandon json_encode in favor of manual string concatenation. Instead, you should leverage the built-in pretty-printing capabilities that have been available for many years.

In PHP 5.4 and later, the JSON_PRETTY_PRINT flag was introduced directly into the json_encode() function. This allows you to format the output with newlines and indentation automatically without writing complex regex logic or string replacement loops. The syntax is straightforward: pass the second parameter as JSON_PRETTY_PRINT.

$data = [
    'product_name' => 'prod1',
    'val1' => 1,
    'val2' => 8
];

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

This produces the desired multi-line structure. However, there is a significant nuance regarding default indentation that you must account for. By default, json_encode uses two spaces per level of nesting when this flag is active. If your client requires a specific indentation style—such as four spaces or tabs—you cannot rely on the default behavior alone.

To customize the indentation, you must pass an associative array as the second argument to json_encode. The key for the options should be JSON_UNESCAPED_SLASHES (if needed) or simply an integer representing the number of spaces, though strictly speaking, the standard function expects a bitmask of flags. In PHP 5.4+, you can actually pass an array of options where the second element defines the indentation size.

$output = json_encode($data, JSON_PRETTY_PRINT, 2); // 2 spaces default
// For 4 spaces:
$output = json_encode($data, JSON_PRETTY_PRINT, 4); 

Wait, that is a common misconception. The third argument in json_encode is reserved for specific flags like JSON_UNESCAPED_UNICODE, not an integer for spacing. To set custom indentation size in PHP 5.4+, you need to use the JsonConfig class or simply pass the flags in a different order depending on your exact version. Actually, the most reliable way to specify indentation size in standard PHP is via the second argument being an array of options if available in newer versions, but historically, PHP does not support passing a specific integer for spaces directly as a bitmask.

Correction: In standard PHP json_encode, the third argument accepts flags. To change indentation width, you typically cannot do it purely via flags in older PHP versions without external libraries. However, starting from PHP 5.4, there isn't a direct flag to set space count other than the default 2 spaces. If you need more control, you might look into json_encode variants or use the JsonFormatter logic, but strictly speaking, standard json_encode with JSON_PRETTY_PRINT defaults to 2 spaces.

If you are on PHP 5.2.x as mentioned in the source scenario, the JSON_PRETTY_PRINT flag does not exist. In that specific legacy environment, you would have to use a third-party library like php-json or manually construct the string. Manually inserting newlines is error-prone because JSON syntax requires commas after keys but not after the last item in an object. A naive str_replace(',\n', ',\n' ...) approach will break valid JSON structures unless you carefully handle the trailing commas in arrays and objects.

For modern PHP development (7.x or 8.x), sticking to native functions is preferred. If your environment supports it, ensure you are using a version where json_encode handles the flags correctly. There are also streaming encoders available for handling massive datasets that cannot fit into memory, but for typical file generation tasks, the standard function suffices.

If you are building an application with Laravel, the underlying PHP engine will handle these flags identically. You can find utility examples and best practices for JSON manipulation in resources like https://laravelcompany.com, which often discusses output formatting in the context of API responses and file exports. However, remember that while formatting improves readability, it increases file size. If the file is meant for strict machine consumption (e.g., a configuration parser), minification might actually be better unless human inspection is explicitly required.

Always verify the target PHP version before assuming flag availability. The JSON_PRETTY_PRINT flag was added in 5.4.0. Using it on 5.2.x will result in a warning or simply ignore the flag, leaving you with minified output. In legacy environments, manually writing the structure is fragile; using a dedicated JSON library is the robust alternative.

Our network