Home >Backend Development >PHP Tutorial >How Can I Pretty-Print JSON Output in PHP?

How Can I Pretty-Print JSON Output in PHP?

Linda Hamilton
Linda HamiltonOriginal
2024-12-27 18:10:10385browse

How Can I Pretty-Print JSON Output in PHP?

JSON beautified output: PHP secrets

In PHP, JSON data is usually output through the json_encode function. However, when the data size is large, the results can be difficult to read because the data is often compressed to a single row.

To avoid this, PHP 5.4 and above provides the JSON_PRETTY_PRINT option that inserts newlines and indentation, making the JSON output readable.

Instructions for use:

  1. Change JSON_PRETTY_PRINT Passed as the second argument to the json_encode function:
$data = ['a' => 'apple', 'b' => 'banana', 'c' => 'catnip'];
$json_string = json_encode($data, JSON_PRETTY_PRINT);
  1. Then, $json_st The ring will contain prettified JSON output like this:
{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}

Using JSON_PRETTY_PRINT, PHP developers can easily output easy-to-read JSON responses, thereby enhancing debuggability sex and user experience.

The above is the detailed content of How Can I Pretty-Print JSON Output in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn