2014-02-14 181 views
0

有文件JSON問題防止覆蓋文件

http://jsfiddle.net/XLkqH/

了我的代碼和我的代碼的PHP是在這裏:

<?php 
    $json = $_POST['json']; 

    /* sanity check */ 
    $file = fopen('../js/json/nameplaylist.json','w+'); 
    fwrite($file, $json); 
    fclose($file); 

?> 

我需要的是,當名字被保存,我不能覆蓋整個文件竇,我將其添加到列表的末尾,然後顯示它在選擇

解決方案:

<?php 
$in_array = json_decode($_POST['json'], true); 
$file_array = json_decode(file_get_contents('../js/json/nameplaylist.json'), true); 
$new_array = array_merge($file_array, $in_array); 
file_put_contents('../js/json/nameplaylist.json', json_encode($new_array)); 
?> 
+0

所以你想合併現有的文件與新的數據,或只是將新的數據添加到現有文件的末尾?爲什麼不只是讀取現有的文件內容,合併爲數組,然後替換? – Anthony

+0

嘗試從文件中重新獲取數據,然後將新$ json添加到舊數據中,然後重寫它。 – aerojun

+1

(僅供參考)使用'a +'附加。 'w +'會覆蓋內容。 –

回答

0

我想這是你想要什麼:

$in_array = json_decode($_POST['json'], true); 
$file_array = json_decode(file_get_contents('../json/nameplaylist.json'), true); 
$new_array = array_merge($file_json, $in_json); 
file_put_contents('../json/nameplaylist.json', json_encode($new_array)); 

你不能只是添加新的JSON到文件的末尾,因爲那麼該文件將包含許多不同的JSON陣列。你必須連接數組,然後重寫整個文件。

+0

如果file_get_contents找不到該文件(因爲它首先與該文件名進行復飛),json_decode是否會返回空數組? – Anthony

+0

不,它不會。在部署應用程序之前,您可以簡單地用'[]'初始化文件。或者你可以添加錯誤檢查到我的代碼來設置'$ file_array = array();'如果它是空的。 – Barmar

+0

我有一個問題,它的即時通訊找到,但當試圖保存json返回空文件json如何修復? – Cazs