如何将表单数据添加到JSON文件


How to add form data to a JSON file?

现在我有这个表单:

<form name='steampaypalinfo' action='profile.php' method='post'>
PayPal Email: <br><input type='email' name='paypal'><br>
Steam Trade URL: <br><input type='text' name='tradeurl'><br><br>
<input type='submit' value='Update' name='submit'>
</form>

我在PHP中像这样检索数据:

if (isset($_POST['submit'])) {
if (empty($_POST['paypal'])) {
    $paypalerror = "PayPal email is required!";
} else {
    $paypalemail = $_POST['paypal'];
}
if (empty($_POST['tradeurl'])) {
$tradeurlerror = "Steam Trade URL is required!";
} else {
    $tradeurl = $_POST['tradeurl'];
}

如您所见,我将表单数据(电子邮件和链接)存储到两个变量paypalemail和tradeurl中。

现在我想将这些数据添加到我已经制作的JSON文件中。JSON文件现在看起来是这样的:

{
"response": {
    "players": [
        {
            "steamid": "76561198064105349",
            "communityvisibilitystate": 3,
            "profilestate": 1,
            "personaname": "PUGLORD",
            "lastlogoff": 1445136051,
            "commentpermission": 2,
            "profileurl": "http://steamcommunity.com/id/ashland3000/",
            "avatar": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f6/f65576bed67efe25134478a63ae51c782b58de65.jpg",
            "avatarmedium": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f6/f65576bed67efe25134478a63ae51c782b58de65_medium.jpg",
            "avatarfull": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/f6/f65576bed67efe25134478a63ae51c782b58de65_full.jpg",
            "personastate": 0,
            "realname": "Jakob",
            "primaryclanid": "103582791439857810",
            "timecreated": 1337817157,
            "personastateflags": 0,
            "loccountrycode": "US",
            "locstatecode": "NY"
        }
    ]
}
}

我想要的数据paypalemail和tradeurl数据进入球员数组。我读过关于使用file_put_contents或fwrite,但这些似乎都不起作用。

问题:如何将PayPal和Steam URL数据添加到已经制作的JSON文件中?我如何将该数据添加到JSON文件中已经制作的数据并正确格式化它?

谢谢你,任何帮助将是伟大的!

编辑我试过了:

$file = file_get_contents("cache/players/{$steam64}.json");
$json = json_decode($file, true);
$player_array['paypalemail'] = $paypalemail;
$json = json_encode($player_array);
$file = fopen("cache/players/{$steam64}.json", 'w');
fwrite($file, $json);
fclose($file);

它工作,但它覆盖JSON文件中的数据。我如何添加它而不覆盖它?

应该像这样:

$file = file_get_contents('players.json');
$json = json_decode($file, true); //second parameter, return as associative array
$player_array = &$json['response']['players'][0];
//lets setup new keys
$player_array['paypalemail'] = "johanroure@cool.com";
//whatever you want to add
$new_json = json_encode($json,JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); //pretty and without slashes
$file = fopen('players.json', 'w'); //w set pointer to beginning and truncate to 0 :D
fwrite($file, $new_json);
fclose($file);