How to Pretty Print JSON in PHP


We can pretty print JSON String in PHP using the json_encode() function and by making use of the JSON_PRETTY_PRINT option along with it.

Let's take a look by an example.


Unformatted JSON String

{"countries":[{"name":"Japan","cities":[{"name":"Tokyo","area":"Kanto"},{"name":"Osaka","area":"Kansai"}]},{"name":"China","cities":[{"name":"Beijing","area":"Beijing Municipality"},{"name":"Shanghai","area":"Shanghai Municipality"}]},{"name":"Australia","cities":[{"name":"Sydney","area":"New South Wales"},{"name":"Melbourne","area":"Victoria"}]}]}


PHP Code

<?php


$unformattedCityJSON = '{"countries":[{"name":"Japan","cities":[{"name":"Tokyo","area":"Kanto"},{"name":"Osaka","area":"Kansai"}]},{"name":"China","cities":[{"name":"Beijing","area":"Beijing Municipality"},{"name":"Shanghai","area":"Shanghai Municipality"}]},{"name":"Australia","cities":[{"name":"Sydney","area":"New South Wales"},{"name":"Melbourne","area":"Victoria"}]}]}';

$data = json_decode($unformattedCityJSON, true);
$prettifiedCityJSON = json_encode($data, JSON_PRETTY_PRINT);
echo $prettifiedCityJSON;

?>

Prettified JSON Output:

{
    "countries": [
        {
            "name": "Japan",
            "cities": [
                {
                    "name": "Tokyo",
                    "area": "Kanto"
                },
                {
                    "name": "Osaka",
                    "area": "Kansai"
                }
            ]
        },
        {
            "name": "China",
            "cities": [
                {
                    "name": "Beijing",
                    "area": "Beijing Municipality"
                },
                {
                    "name": "Shanghai",
                    "area": "Shanghai Municipality"
                }
            ]
        },
        {
            "name": "Australia",
            "cities": [
                {
                    "name": "Sydney",
                    "area": "New South Wales"
                },
                {
                    "name": "Melbourne",
                    "area": "Victoria"
                }
            ]
        }
    ]
}

Example Screenshot

PHP Prettify JSON String Example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap