How to Update/Edit JSON File in PHP?

Sep 05, 2022

.

Admin

How to Update/Edit JSON File in PHP?

Hi Dev,

In this tutorial, you will learn How to Update Json File in php. if you want to see example of How to Update Json Data in php then you are a right place. we will help you to give example of PHP Read and Write Json File. Here you will learn PHP Modify Json File.

Here, I will give the following example of how to update/edit json file in php program, we will use The file_get_contents() this function reads a file into a string, The json_decode() function is use to JSON encoded string and convert into a PHP variable and file_put_contents() function is use to save file.

Example: update/edit json file


I simply created data.json file with content as like below:

data.json

[

{

"id": 1,

"name": "Hardik Savani",

"email": "hardik@gmail.com"

},

{

"id": 2,

"name": "Jaydeep Pathar",

"email": "jaydeep@gmail.com"

},

{

"id": 3,

"name": "Vivek Pathar",

"email": "vivek@gmail.com"

}

]

index.php

<?php

//get file

$datas = file_get_contents('data.json');

//Decode the JSON data into a PHP array.

$datasDecoded = json_decode($datas, true);

// Create Array to json file for Add data

$datasDecoded[] = ["id" => 4, "name" => "Mehul Bagda", "email" => "mehul@gmail.com"];

$datasDecoded[] = ["id" => 5, "name" => "Nikhil Thummer", "email" => "nikhil@gmail.com"];

//Encode the array back into a JSON string.

$json = json_encode($datasDecoded);

//Save the file.

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

?>

Output:

result.json

[

{

"id":1,

"name":"Hardik Savani",

"email":"hardik@gmail.com"

},

{

"id":2,

"name":"Jaydeep Pathar",

"email":"jaydeep@gmail.com"

},

{

"id":3,

"name":"Vivek Pathar",

"email":"vivek@gmail.com"

},

{

"id":4,

"name":"Mehul Bagda",

"email":"mehul@gmail.com"

},

{

"id":5,

"name":"Nikhil Thummer",

"email":"nikhil@gmail.com"

}

]

I hope it could help you...

#PHP