Pretty printing of JSON using PHP and Javascript

In this post, I would like to explain how to display JSON data in a pretty way. In the earlier posts, I have explained how to create API. This post is extended to display JSON, so that easy to understand and readable. To print the JSON data pretty way we have two approaches, we can use PHP and We can use Javascript.

Pretty printing of JSON using PHP and Javascript by Anil Kumar Panigrahi

Pretty printing of JSON using PHP and Javascript by Anil Kumar Panigrahi

Readable pretty format using Javascript

Javascript code:

<script>
var data = [{"Product":{"name":"iPhone","series":"x","price":"$100.00"}}]

document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
</script>

HTML code:

<pre id="json"></pre>

Completed code using Javascript:

<!DOCTYPE html>

<html>

<head>
        <title>JSON Formatter</title>
</head>

<body>
<pre id="json"></pre>

<script>

    var data = [{"Product":{"name":"iPhone","series":"x","price":"$100.00"}}]
    document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);

</script>

</body>
</html>

Readable pretty format using PHP

HTML form code:

<form action="" method="POST">
        <textarea name="json_text" style="width: 500px; height: 200px;"></textarea>
        <input type="submit" />
</form>

PHP code:
Read that textarea text and display as readable format

<?php
$json = '';
if (isset($_POST['json_text']) && !empty($_POST['json_text'])) {
    $struct = json_decode($_POST['json_text'], true);
    $json = json_encode($struct, JSON_PRETTY_PRINT);
    header('Content-Type: text/plain');
    echo $json;
    exit;
}
?>

In earlier I have explained PHP headers, so in this I have used ‘text/plain’.

Complete code using PHP

<?php
$json = '';
if (isset($_POST['json_text']) && !empty($_POST['json_text'])) {
    $struct = json_decode($_POST['json_text'], true);
    $json = json_encode($struct, JSON_PRETTY_PRINT);
    header('Content-Type: text/plain');
    echo $json;
    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
        <title>JSON Formatter by Anil Labs</title>
</head>

<body>
<div>
        <strong>Enter your non formated json in here and click submit to get pretty readable json!</strong>
</div>
<form action="" method="POST">
    <textarea name="json_text" style="width: 500px; height: 200px;"></textarea>
    <input type="submit" />
</form>
</body>
</html>

Hope it will use when we working on API documentation.

Anil Kumar Panigrahi

With more than 10 years experience in PHP and Founder of Anil Labs, a blog for PHP and related posts. contributed posts regarding CodeIgniter, CakePHP and Learn PHP online ... Contact : [email protected]

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *