2014-02-14 183 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