Current Location: Home> Latest Articles> How to Format JSON with Line Breaks in PHP to Improve Readability

How to Format JSON with Line Breaks in PHP to Improve Readability

gitbox 2025-07-21

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is widely used for data transmission between clients and servers. Working with JSON data in PHP, especially in API development, is very common and convenient.

Why Implement Line Breaks in JSON?

In practical development, when debugging or logging JSON data, well-formatted line breaks and indentation greatly enhance readability. Raw JSON is usually a compact single-line string, making it hard to quickly understand the data structure. Therefore, adding line breaks to JSON output is essential to improve code quality and debugging efficiency.

How to Implement JSON Line Breaks in PHP?

PHP’s built-in json_encode function supports various options. Among them, the JSON_PRETTY_PRINT option enables JSON output with line breaks and indentation for better readability.

Creating a Sample Array

First, define an array containing user information:

$data = [
    "name" => "John Doe",
    "age" => 30,
    "city" => "New York"
];
?>

Encoding the Array as Formatted JSON

Use the json_encode function with the JSON_PRETTY_PRINT option enabled:

$jsonData = json_encode($data, JSON_PRETTY_PRINT);
echo $jsonData;
?>

Complete Example Code

Below is a complete example that converts the array into JSON with line breaks and indentation:

$data = [
    "name" => "John Doe",
    "age" => 30,
    "city" => "New York"
];
$jsonData = json_encode($data, JSON_PRETTY_PRINT);
echo $jsonData;
?>

Output Result

The output of the above code will be:

{
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

This formatted output clearly shows the JSON data structure, making it easier to read and maintain.

Summary

By using PHP’s built-in json_encode function along with the JSON_PRETTY_PRINT option, you can easily achieve line breaks and indentation in JSON output. This simple and efficient method is suitable for any scenario where you want to improve JSON readability, helping developers enhance debugging and data presentation.

If you have more questions about handling JSON in PHP, feel free to explore further resources or engage in discussions.