PHP Program to generate a JSON file

What is meant by JSON?

JSON stands for JavaScript Object Notation. JSON is used to send and receive data from the web. JSON is a plain text written in JavaScript object notation. JSON is a platform-independent language.

How can we generate a JSON file using PHP?

In this program, we are generating a JSON file using PHP. For that first, we have to initialize an associative array arr[] with values in it. After that, we have to encode the array arr[] to the JSON  using the built-in function json_encode() and assign it to the variable json and to display the file we can print the value of variable json. Then to generate the JSON file we can use the built-in function file_put_contents() with "details.json" (filename) and value of the variable json as the argument of the function

Syntax


json_encode(value, options, depth)
file_put_contents(filename, data, mode, context)
 

ALGORITHM

Step 1: Initialize an associative array arr[] with values in it

Step 2: Encode the array arr[] to the JSON  using the built-in function json_encode() and assign it to the variable json

Step 3: To display the file we can print the value of variable json

Step 4: To generate the JSON file we can use the built-in function file_put_contents() with "details.json" (filename) and value of the variable json as the argument of the function

PHP Source Code

                                          <?php
$arr = array(
 "0" => array(
  "id" => "101",
  "name" => "Jhon",
  "language" => "PHP"
 ),
 "1" => array(
  "id" => "102",
  "name" => "Doe",
  "language" => "python"
 )
); $js
echo "$json";
file_put_contents("details.json", $json);
?>
                                      

OUTPUT

[{"id":"101","name":"Jhon","language":"PHP"},{"id":"102","name":"Doe","language":"python"}]