Skip to content
PHP Logo

Are there any PHP functions or options that can help format JSON data for better readability in files?

When writing JSON data to files in PHP, the output can often be difficult to read and understand due to its compact format. To improve readability, you can use the `JSON_PRETTY_PRINT` option when encoding the data with `json_encode()`. This option will format the JSON data with indentation and line breaks, making it easier to read.

php
$data = array(
    'name' => 'John Doe',
    'age' => 30,
    'email' => 'johndoe@example.com'
);

$jsonData = json_encode($data, JSON_PRETTY_PRINT);

file_put_contents('data.json', $jsonData);