Home >Backend Development >PHP Tutorial >How Can I Pretty-Print JSON Data in PHP?
Presenting JSON Data Elegantly with PHP
When handling JSON data in PHP, you may encounter the need to format it in a structured and aesthetically pleasing manner. By default, json_encode() outputs data as a flat, single-line string. However, there's a solution that Facebook has implemented: JSON_PRETTY_PRINT.
Introduced in PHP 5.4, JSON_PRETTY_PRINT is an option that you can pass to json_encode() to transform your JSON data into a human-readable format. It indents and line-breaks the data, making it easier to view and comprehend.
To demonstrate, let's use the example from the question:
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip'); header('Content-type: text/javascript'); echo json_encode($data, JSON_PRETTY_PRINT);
Output:
{ "a": "apple", "b": "banana", "c": "catnip" }
As you can see, the output is now formatted, making it easier to read, especially for large data sets. While there may have been workarounds in the past, JSON_PRETTY_PRINT provides a simple and elegant solution to present JSON data in a visually appealing manner.
The above is the detailed content of How Can I Pretty-Print JSON Data in PHP?. For more information, please follow other related articles on the PHP Chinese website!