如何使用 PHP 更新/编辑 JSON 文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17806224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update/edit a JSON file using PHP
提问by user475464
Here is my JSON
这是我的JSON
[
{
"activity_code":"1",
"activity_name":"FOOTBALL"
},
{
"activity_code":"2",
"activity_name":"CRICKET"
}
]
I need to update {"activity_code":"1","activity_name":"FOOTBALL"}
to {"activity_code":"1","activity_name":"TENNIS"}
based on activity_code
我需要更新{"activity_code":"1","activity_name":"FOOTBALL"}
到{"activity_code":"1","activity_name":"TENNIS"}
基于activity_code
How can I achieve this in PHP?
我怎样才能在 PHP 中实现这一点?
回答by Brewal
First, you need to decode it :
首先,您需要对其进行解码:
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);
Then change the data :
然后更改数据:
$data[0]['activity_name'] = "TENNIS";
// or if you want to change all entries with activity_code "1"
foreach ($data as $key => $entry) {
if ($entry['activity_code'] == '1') {
$data[$key]['activity_name'] = "TENNIS";
}
}
Then re-encode it and save it back in the file:
然后重新编码并将其保存回文件中:
$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);