使用PHP将数据附加到.JSON文件

时间:2011-10-25 20:18:25

标签: php json

我有这个.json文件:

[
    {
        "id": 1,
        "title": "Ben\\'s First Blog Post",
        "content": "This is the content"
    },
    {
        "id": 2,
        "title": "Ben\\'s Second Blog Post",
        "content": "This is the content"
    }
]

这是我的PHP代码:

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

$fp = fopen('results.json', 'a');
fwrite($fp, json_encode($data));
fclose($fp);

问题是,我不确定如何实现它。我每次提交表单时都会调用上面的代码,所以我需要增加ID并使[{保持有效的JSON结构,这可能吗?

8 个答案:

答案 0 :(得分:33)

$data[] = $_POST['data'];

$inp = file_get_contents('results.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);

答案 1 :(得分:22)

这已经采用了上面的例子并将其移至php。这将跳转到文件末尾并添加新数据而不将所有文件读入内存。

// read the file if present
$handle = @fopen($filename, 'r+');

// create the file if needed
if ($handle === null)
{
    $handle = fopen($filename, 'w+');
}

if ($handle)
{
    // seek to the end
    fseek($handle, 0, SEEK_END);

    // are we at the end of is the file empty
    if (ftell($handle) > 0)
    {
        // move back a byte
        fseek($handle, -1, SEEK_END);

        // add the trailing comma
        fwrite($handle, ',', 1);

        // add the new json string
        fwrite($handle, json_encode($event) . ']');
    }
    else
    {
        // write the first event inside an array
        fwrite($handle, json_encode(array($event)));
    }

        // close the handle on the file
        fclose($handle);
}

答案 2 :(得分:14)

你通过盲目地附加文字来破坏你的json数据。 JSON不是一种可以像这样操作的格式。

你必须加载你的json文本,解码它,操纵结果数据结构,然后重新编码/保存它。

<?php

$json = file_get_contents('results.json');
$data = json_decode($json);
$data[] = $_POST['data'];
file_put_contents('results.json', json_encode($data));

假设您已将[1,2,3]存储在您的文件中。您的代码可以将其转换为[1,2,3]4,这在语法上是错误的。

答案 3 :(得分:4)

如果要在示例中显示另一个数组元素添加到JSON文件,请打开文件并搜索到最后。如果文件已有数据,则向后搜索一个字节以覆盖最后一个条目后的],然后写入,加上新数据减去新数据的初始[。否则,它是你的第一个数组元素,所以只需正常编写你的数组。

抱歉,我不太了解PHP发布实际代码,但是我已经在Obj-C中完成了这一点,并且允许我首先避免读取整个文件只是为了添加到最后:

NSArray *array = @[myDictionary];
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];
FILE *fp = fopen(fname, "r+");
if (NULL == fp)
    fp = fopen(fname, "w+");
if (fp) {
    fseek(fp, 0L, SEEK_END);
    if (ftell(fp) > 0) {
        fseek(fp, -1L, SEEK_END);
        fwrite(",", 1, 1, fp);
        fwrite([data bytes] + 1, [data length] - 1, 1, fp);
    }
    else
        fwrite([data bytes], [data length], 1, fp);
    fclose(fp);
}

答案 4 :(得分:3)

我用于将其他JSON数组附加到JSON文件的示例代码。

$additionalArray = array(
    'id' => $id,
    'title' => $title,
    'content' => $content
);

//open or read json data
$data_results = file_get_contents('results.json');
$tempArray = json_decode($data_results);

//append additional json to json file
$tempArray[] = $additionalArray ;
$jsonData = json_encode($tempArray);

file_put_contents('results.json', $jsonData);   

答案 5 :(得分:0)

/*
 * @var temp 
 * Stores the value of info.json file
 */
$temp=file_get_contents('info.json');

/*
 * @var temp
 * Stores the decodeed value of json as an array
 */
$temp= json_decode($temp,TRUE);

//Push the information in temp array
$temp[]=$information;

// Show what new data going to be written
echo '<pre>';
print_r($temp);

//Write the content in info.json file
file_put_contents('info.json', json_encode($temp));
}

答案 6 :(得分:0)

我编写了此PHP代码以将json添加到json文件。 该代码会将整个文件括在方括号中,并用逗号分隔代码。

<?php

//This is the data you want to add
//I  am getting it from another file
$callbackResponse = file_get_contents('datasource.json');

//File to save or append the response to
$logFile = "results44.json";


//If the above file does not exist, add a '[' then 
//paste the json response then close with a ']'


if (!file_exists($logFile)) {
  $log = fopen($logFile, "a");
  fwrite($log, '['.$callbackResponse.']');
  fclose($log);                      
}


//If the above file exists but is empty, add a '[' then 
//paste the json response then close with a ']'

else if ( filesize( $logFile) == 0 )
{
     $log = fopen($logFile, "a");
  fwrite($log, '['.$callbackResponse.']');
  fclose($log);  
}


//If the above file exists and contains some json contents, remove the last ']' and 
//replace it with a ',' then paste the json response then close with a ']'

else {

$fh = fopen($logFile, 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);
fclose($fh); 

$log = fopen($logFile, "a");
  fwrite($log, ','.$callbackResponse. ']');
  fclose($log); 

}

    ?>

好运

答案 7 :(得分:0)

使用PHP将数据附加到.json文件中

  • 也保持有效的json结构
  • 不追加数组。
  • 将json附加到QuesAns .json文件中。
  • 覆盖文件中的数据
   $data = $_POST['data'];
   //$data= 
   
   array("Q"=>"QuestThird","A"=>"AnswerThird");
        
   $inp = file_get_contents('QuesAns.json');
   //$inp='[{"Q":"QuestFurst","A":"AnswerFirst"},{"Q":"Quest second","A":"AnswerSecond"}]';     
  
   /**Convert to array because array_push working with array**/
   $tempArray = json_decode($inp,true);
        
   array_push($tempArray, $data);
   print_r($tempArray);
   echo'<hr>';

   $jsonData = json_encode($tempArray);

   file_put_contents('QuesAns.json', $jsonData);
   
   print($jsonData);

输出:

Array([0] => Array([Q] => QuestFurst [A] => AnswerFirst)[1] => Array([Q] => Quest second [A] => AnswerSecond)[2] = >数组([Q] => QuestThird [A] => AnswerThird))


[{“ Q”:“ QuestFurst”,“ A”:“ AnswerFirst”},{“ Q”:“ Quest second”,“ A”:“ AnswerSecond”},{“ Q”:“ QuestThird”, “ A”:“ AnswerThird”}]