Json_Encode() Pretty Print Using PHP

Dec 20, 2022

2 mins read

Published in

Using json_encode with JSON_PRETTY_PRINT parameters helps to pretty print JSON and returns. We can use JSON to store and retrieve the data used in applications. It’s platform-independent and advanced interoperability in mind.

PHP is a widely used language that works with JSON and provides the json_encode() function.

What is json_encode() ?

Json_Encode() is a function in PHP that takes a data structure (array, php objects, associative array) as input and returns a JSON encoded string. It’s inbuilt function of PHP to convert PHP array, objects and generate JSON string. It also provide functionality of formatting JSON data by providing options to the json_encode().

JSON encode() is a PHP function that converts a given string to its JSON representation. This is done by converting characters to UTF-8 and wrapping them in curly braces’ ( “{” and “}”).

Syntax :

string json_encode( $value, $option, $depth )

Example : using JSON_PRETTY_PRINT option

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<?php
// Declare an array 
$movie = array(
    "name"=>"Avatar ",
    "locaton"=>"Pandora",
    );

// Using json_encode() 
$json = json_encode($movie,
  JSON_PRETTY_PRINT);
print_r($json);
?>

Result

{
    "name": "Avatar ",
    "locaton": "Pandora"
}

Result without JSON_PRETTY_PRINT

{"name":"Avatar ","locaton":"Pandora"}

List of Option in json_encode() function

NAME Description
JSON_FORCE_OBJECT Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty.
JSON_HEX_QUOT All " are converted to \u0022.
JSON_HEX_TAG All < and > are converted to \u003C and \u003E.
JSON_HEX_AMP All & are converted to \u0026.
JSON_HEX_APOS All ’ are converted to \u0027.
JSON_INVALID_UTF8_IGNORE Ignore invalid UTF-8 characters. Available as of PHP 7.2.0.
JSON_INVALID_UTF8_SUBSTITUTE Convert invalid UTF-8 characters to \0xfffd (Unicode Character ‘REPLACEMENT CHARACTER’) Available as of PHP 7.2.0.
JSON_NUMERIC_CHECK Encodes numeric strings as numbers.
JSON_PARTIAL_OUTPUT_ON_ERROR Substitute some unencodable values instead of failing.
JSON_PRESERVE_ZERO_FRACTION Ensures that float values are always encoded as a float value.
JSON_PRETTY_PRINT Use whitespace in returned data to format it.
JSON_UNESCAPED_LINE_TERMINATORS The line terminators are kept unescaped when JSON_UNESCAPED_UNICODE is supplied
JSON_UNESCAPED_SLASHES Don’t escape /.
JSON_UNESCAPED_UNICODE Encode multibyte Unicode characters literally (default is to escape as \uXXXX).
JSON_THROW_ON_ERROR if an error occurs instead of setting the global error state that is retrieved with json_last_error() and json_last_error_msg()

Know More about PHP JSON_ENCODE :

Sharing is caring!