How to create JSON formatted text in PHP

By Faruque Ahamed Mollick

The common use of JSON is to interchange data. JSON or JavaScript Object Notation is a lightweight data-interchange format. The format of JSON is easy for both human being and machine.

Many time it may be needed to interchange data with someone else. For example, if you may create a JSON format for representing weather forecast data and another one can create a weather forecast mobile app that is retrieving data from your JSON format.

In this post, I am going to show you how you can create JSON formatted text using PHP programming language. I am going to show you so easy example code for creating JSON formatted text in PHP.

Below is given a simple PHP code:

<?php
$array_for_json = array("value 1", "value 2", "value 3", "value 4");

$create_json = json_encode($array_for_json);

echo $create_json;
?>

When you run the above PHP code on the server, it will show the below result:



["value 1","value 2","value 3","value 4"]

PHP already has an inbuilt json_encode() function which can be used to encoding JSON formatted data easily. json_encode() function was first introduced in PHP 5.2. After that day encoding JSON became so easy in PHP and it helps developers a lot.

Another example of encoding JSON from JSON object:

JSON objects are surrounded by curly braces {} and written in key/value pairs. Below is the PHP code to encode JSON from key value pairs or object:

<?php
$json_arr = array(
'obj 1' => "value 1",
'obj 2' => "value 2",
'obj 3' => "value 3"
);

echo json_encode($json_arr, JSON_PRETTY_PRINT);

?>

You can see in the above code that I have used JSON_PRETTY_PRINT which will nicely display JSON formatted data line by line. Below is the given output:

{
    "obj 1": "value 1",
    "obj 2": "value 2",
    "obj 3": "value 3"
}

 

Leave a Reply

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