Advertisement
Intermediate PHP, JSON Handling in PHP

How do you control the depth and formatting of json_encode output, such as pretty printing JSON for readability or handling deeply nested data structures?

Short answer

The json_encode function accepts an optional flags parameter that lets you control formatting behavior, such as JSON_PRETTY_PRINT to produce nicely indented, human readable output useful for debugging or configuration files, and it also accepts a depth parameter controlling how…

Save PHP mock interview
Advertisement
AModel answer
The json_encode function accepts an optional flags parameter that lets you control formatting behavior, such as JSON_PRETTY_PRINT to produce nicely indented, human readable output useful for debugging or configuration files, and it also accepts a depth parameter controlling how deeply nested arrays or objects it will process before throwing an error, which is a useful safeguard against accidentally encoding an extremely deep or circular data structure.
$data = ['user' => ['name' => 'Ali', 'roles' => ['admin', 'editor']]];
echo json_encode($data, JSON_PRETTY_PRINT);
Real-world example
A configuration management tool uses JSON_PRETTY_PRINT when writing a configuration file to disk, ensuring the resulting file remains easy for a human developer to read and manually edit if ever needed.
Likely follow-ups
  • What other useful flags does json_encode support besides JSON_PRETTY_PRINT?
  • What happens if you try to encode a PHP array containing a circular reference?
Related topics