2015-10-18 130 views
3

現在我有這樣的形式:如何將表單數據添加到JSON文件?

<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文件覆蓋的數據。我如何添加它但不覆蓋它?

回答

0

應該是這樣的:

$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'] = "[email protected]"; 
//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); 
+0

看我的更新。 – Jakob