How to Format JSON in PHP
Feb 05, 2026 3 min read
Formatting JSON in PHP is extremely straightforward. The built-in json_encode() function accepts a bitmask of options. By passing the JSON_PRETTY_PRINT constant, you get beautifully indented JSON output.
Example Code
PHP
<?php
$data = [
"name" => "John",
"age" => 30,
"city" => "New York",
"skills" => ["PHP", "Laravel"]
];
// Use JSON_PRETTY_PRINT flag to indent the JSON
$formattedJson = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
echo $formattedJson;
?> Common Use Cases
- Outputting readable JSON APIs directly from PHP scripts
- Saving JSON representations of objects to files
- Debugging variables directly
💡 Pro Tips for PHP
- Always combine
JSON_PRETTY_PRINTwithJSON_UNESCAPED_SLASHESif your strings include URLs to prevent escaping. - If you are containing Unicode characters, add
JSON_UNESCAPED_UNICODE. - The indent level in PHP is hardcoded to 4 spaces, so you cannot change it out of the box dynamically.
Debug PHP JSON Fast
Skip the <code>echo json_encode()</code> cycle. Paste your raw data into our formatter for a clear, tree-view perspective of your PHP arrays.