We build a PHP script that feeds JSON data to another script.  ur script builds data into a large associative array, and then outputs the data using json_encode.

Here is an example script:

Php Code
$data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
header('Content-type: text/javascript');
echo json_encode($data);
  • The above code yields the following output:
Php Code
{"a":"apple","b":"banana","c":"catnip"}
  • This is great if you have a small amount of data, but I’d prefer something along these lines:
Php Code
{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}
  • Is there a way to do this in PHP without an ugly hack? It seems like someone at Facebook figured it out.
  • php json pretty-print

PHP 5.4 offers the JSON_PRETTY_PRINT option for use with the json_encode() call.

http://php.net/manual/en/function.json-encode.php

Php Code
<?php
...
$json_string = json_encode($data, JSON_PRETTY_PRINT);

This function will take JSON string and indent it very readable. It also should be convergent,

Php Code
prettyPrint( $json ) === prettyPrint( prettyPrint( $json ) )

Input

Php Code
{"key1":[1,2,3],"key2":"value"}

Output

Php Code
{
    "key1": [
        1,
        2,
        3
    ],
    "key2": "value"
}

Code:

Php Code
function prettyPrint( $json )
{
    $result = '';
    $level = 0;
    $in_quotes = false;
    $in_escape = false;
    $ends_line_level = NULL;
    $json_length = strlen( $json );

    for( $i = 0; $i < $json_length; $i++ ) {
        $char = $json[$i];
        $new_line_level = NULL;
        $post = "";
        if( $ends_line_level !== NULL ) {
            $new_line_level = $ends_line_level;
            $ends_line_level = NULL;
        }
        if ( $in_escape ) {
            $in_escape = false;
        } else if( $char === '"' ) {
            $in_quotes = !$in_quotes;
        } else if( ! $in_quotes ) {
Php Code
switch( $char ) {
                case '}': case ']':
                    $level--;
                    $ends_line_level = NULL;
                    $new_line_level = $level;
                    break;

                case '{': case '[':
                    $level++;
                case ',':
                    $ends_line_level = $level;
                    break;

                case ':':
                    $post = " ";
                    break;

                case " ": case "\t": case "\n": case "\r":
                    $char = "";
                    $ends_line_level = $new_line_level;
                    $new_line_level = NULL;
                    break;
            }
        } else if ( $char === '\\' ) {
            $in_escape = true;
Php Code
 }
        if( $new_line_level !== NULL ) {
            $result .= "\n".str_repeat( "\t", $new_line_level );
        }
        $result .= $char.$post;
    }

    return $result;
}
[ad type=”banner”]

We just used the json formatting code here:

http://recursive-design.com/blog/2008/03/11/format-json-with-php/

Php Code
echo json_encode($results, JSON_PRETTY_PRINT);

Which is absolutely right. But it’s not enough, the browser needs to understand the type of data, you can specify the header just before echo-ing the data back to the user.

Php Code
header('Content-Type: application/json');
  • This will result in a well formatted output.
  • Or, if you like extensions you can use JSONView for Chrome.

Simple way for php>5.4:

Php Code
$Data = array('a' => 'apple', 'b' => 'banana', 'c' => 'catnip');
$json= json_encode($Data, JSON_PRETTY_PRINT);
header('Content-Type: application/json');
print_r($json);

Result in browser

Php Code
{
    "a": "apple",
    "b": "banana",
    "c": "catnip"
}
[ad type=”banner”]

How to encode an associative array to a pretty-formatted JSON string, so this doesn’t directly answer the question, but if you have a string that is already in JSON format, you can make it pretty simply by decoding and re-encoding it (requires PHP >= 5.4):

Php Code
$json = json_encode(json_decode($json), JSON_PRETTY_PRINT);

Example:

Php Code
$json_ugly = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$json_pretty = json_encode(json_decode($json_ugly), JSON_PRETTY_PRINT);
echo $json_pretty;

This outputs:

Php Code
{
    "a": 1,
    "b": 2,
    "c": 3,
    "d": 4,
    "e": 5
}

Use <pre> in combination with json_encode() and the JSON_PRETTY_PRINT option:

Php Code
<pre>
    <?php
    echo json_encode($dataArray, JSON_PRETTY_PRINT);
    ?>
</pre>
[ad type=”banner”]

Categorized in: