Sunday, November 17, 2024
Google search engine
HomeLanguagesPHP JSON Pretty Print

PHP JSON Pretty Print

JSON is a JavaScript notation for storing and fetching data. Data is usually stored in JSON, XML, or in some other database. It is a complete language-independent text format. To work with JSON data, PHP uses JSON_PRETTY_PRINT.

We can use the json_encode() function to write the value in a JSON format. We can render every type of array in PHP like a listed array, associative array, and objects to the JSON format. The json_encode() function has a option JSON_PRETTY_PRINT which prettifies the JSON string. We can first prettify the string then use the json_encode() function. It will add some spaces between the characters and makes the string look better. Still, we can use the HTML markers to graze the strings to the new line. We will prettify an associative array in the illustration below. 

Example 1: Create an associative array in the variable  “$name”. Write the keys and their values. Use the json_encode() function on the “$name” variable and pass JSON_PRETTY_PRINT as the second parameter and store the expression.

PHP




<?php
  
// Associative array having name and age
$name = array("Deepak"=>12, "Arun"=>20, "Nandita"=>10);
  
// json_encode function 
$json_pretty = json_encode($name, JSON_PRETTY_PRINT);
echo "<pre>" . $json_pretty . "<pre/>";
?>


Output:

Use the json_encode() and json_decode() functions to prettify the JSON string in PHP: We can use the json_encode() function with the json_decode() function and the JSON_PRETTY_PRINT as the parameters to prettify the JSON string in PHP. 

Example 2: Set the HTTP headers Content-Type to  “application/ json”. Store a raw JSON object the “$json1” variable. Use the json_decode() function on the “$json1” variable. Pass the decrypted JSON object as the first parameter to the json_encode() function and the JSON_PRETTY_PRINT option as the alternate parameter. 

PHP




<?php
  
echo "Json prettify of a string <br>";
header('Content-Type: application/json');
$json1 = '{"Deepak":10,"Arun":20,"Nandita":30,"Amisha":40,"Shubham":50}';
$json2 = json_encode(json_decode($json1), JSON_PRETTY_PRINT);
echo '<pre>' . $json2 . '</pre>';
?>


Output:

RELATED ARTICLES

Most Popular

Recent Comments