How to Create a JSON File in PHP?

03-Apr-2023

.

Admin

How to Create a JSON File in PHP?

Hi Dev,

This post will give you example of How to Create Json File in php. This post will give you simple example of How to Generate Json File in php?. I would like to show you php Create Json File and Write. I would like to show you How to Save Json File in php?. Alright, let’s dive into the steps.

There ara two ways to create json file in php. in the first example, we will use fopen(), fwrite() and fclose() to create a json file. in the second example, we will use file_put_contents() to create json file in php.Let's see both examples with output.

Example 1:


index.php

<?php

// Create Array for json file

$myArray = [

[ "id" => 1, "name" => "Hardik Savani", "email" => "hardik@gmail.com"],

[ "id" => 2, "name" => "Jaydeep Pather", "email" => "jaydeep@gmail.com"],

[ "id" => 3, "name" => "Vivek Pather", "email" => "vivek@gmail.com"]

];

// Create new data.json file

$fp = fopen('data.json', 'w');

// Write data on json file

fwrite($fp, json_encode($myArray, JSON_PRETTY_PRINT));

// Close json file

fclose($fp);

print("data.json File created successfully.");

?>

Output:

After run successfully above example, you will see data.json file saved in your root path and file content will be as the below:

[

{

"id": 1,

"name": "Hardik Savani",

"email": "hardik@gmail.com"

},

{

"id": 2,

"name": "Jaydeep Pather",

"email": "jaydeep@gmail.com"

},

{

"id": 3,

"name": "Vivek Pather",

"email": "vivek@gmail.com"

}

]

Example 2:

index.php

<?php

// Create Array for json file

$myArray = [

[ "id" => 1, "name" => "Hardik Savani", "email" => "hardik@gmail.com"],

[ "id" => 2, "name" => "Jaydeep Pather", "email" => "jaydeep@gmail.com"],

[ "id" => 3, "name" => "Vivek Pather", "email" => "vivek@gmail.com"]

];

// Create json file from array

$data = json_encode($myArray);

file_put_contents('data.json', $data);

print("data.json File created successfully.");

?>

Output:

After run successfully above example, you will see data.json file saved in your root path and file content will be as the below:

[

{

"id": 1,

"name": "Hardik Savani",

"email": "hardik@gmail.com"

},

{

"id": 2,

"name": "Jaydeep Pather",

"email": "jaydeep@gmail.com"

},

{

"id": 3,

"name": "Vivek Pather",

"email": "vivek@gmail.com"

}

]

I hope it could help you...

#PHP