How to Update/Edit JSON File in PHP?
Teams applying “How to Update/Edit JSON File in PHP?” in a production project can use the linked planning resource to record implementation, review and debugging time, then compare that effort with tests and shipped functionality instead of treating activity as performance by itself.
Before copying the example into a live application, confirm version-specific behaviour with the PHP project and test it against the project’s actual database and runtime.
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": "[email protected]"
},
{
"id": 2,
"name": "Jaydeep Pathar",
"email": "[email protected]"
},
{
"id": 3,
"name": "Vivek Pathar",
"email": "[email protected]"
}
]
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" => "[email protected]"];
$datasDecoded[] = ["id" => 5, "name" => "Nikhil Thummer", "email" => "[email protected]"];
//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":"[email protected]"
},
{
"id":2,
"name":"Jaydeep Pathar",
"email":"[email protected]"
},
{
"id":3,
"name":"Vivek Pathar",
"email":"[email protected]"
},
{
"id":4,
"name":"Mehul Bagda",
"email":"[email protected]"
},
{
"id":5,
"name":"Nikhil Thummer",
"email":"[email protected]"
}
]
I hope it could help you...
- How To Use Php Conditional Statement Example
- How to Check if String Contains Regex in PHP?
- PHP Array_column() Function Example
- PHP Generate List of Random Numbers Between 0 and 100 Example
- How to User Login with Facebook in PHP?
- How to Explode Every Character into Array Using PHP Example?
- PHP Form Validation Tutorial
- PHP Convert XML to JSON Example