如何使用PHP更新/编辑JSON文件 [英] How to update/edit a JSON file using PHP

查看:334
本文介绍了如何使用PHP更新/编辑JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 JSON

[
   {
      "activity_code":"1",
      "activity_name":"FOOTBALL"
   },
   {
      "activity_code":"2",
      "activity_name":"CRICKET"
   }
]

我需要根据activity_code

如何用PHP实现呢?

推荐答案

首先,您需要对其进行解码:

First, you need to decode it :

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

然后更改数据:

$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);

这篇关于如何使用PHP更新/编辑JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆