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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

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