How to update data in a JSON file using PHP?
To update the data in a JSON file, you can follow these steps:
- Read the content of a JSON file and decode it into a PHP array or object.
- Update data in an array or object in PHP.
- Re-encode the updated PHP array or object into a JSON formatted string.
- Use the file writing function to write the updated JSON string to the JSON file.
Here is an example code to implement these steps:
<?php
// 读取JSON文件的内容
$jsonString = file_get_contents('data.json');
// 将JSON字符串解码为PHP数组或对象
$data = json_decode($jsonString, true);
// 更新数组或对象中的数据
$data['key'] = 'new value';
// 将更新后的PHP数组或对象重新编码为JSON格式的字符串
$jsonString = json_encode($data);
// 将更新后的JSON字符串写入JSON文件
file_put_contents('data.json', $jsonString);
?>
Please note that this example assumes you already have a JSON file named “data.json” with a property called “key”. You can adjust it according to your own JSON file structure and update requirements.