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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7895335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:35:49  来源:igfitidea点击:

Append data to a .JSON file with PHP

phpjson

提问by benhowdle89

I have this .json file:

我有这个 .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"
    }
]

This is my PHP code:

这是我的 PHP 代码:

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

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

The thing is, I'm not exactly sure how to achieve it. I'm going to call this code above every time a form is submitted, so I need the ID to increment and to also keep the valid JSON structure with [and {, is this possible?

问题是,我不确定如何实现它。我要呼吁每一个表单提交的时候上面这段代码,所以我需要的ID,以增量,也保持有效的JSON结构[{,这可能吗?

回答by Tim

$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);

回答by Tom Martin

This has taken the above c example and moved it over to php. This will jump to the end of the file and add the new data in without reading all the file into memory.

这已经采用了上面的 c 示例并将其移至 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);
}

回答by Marc B

You're ruining your json data by blindly appending text to it. JSON is not a format that can be manipulated like this.

您通过盲目地向其附加文本来破坏您的 json 数据。JSON 不是可以像这样操作的格式。

You'll have to load your json text, decode it, manipulate the resulting data structure, then re-encode/save it.

您必须加载 json 文本,对其进行解码,操作生成的数据结构,然后重新编码/保存它。

<?php

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

Let's say you've got [1,2,3]stored in your file. Your code could turn that into [1,2,3]4, which is syntactically wrong.

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

回答by spstanley

If you want to add another array element to a JSON file as your example shows, open the file and seek to the end. If the file already has data, seek backwards one byte to overwrite the ]following the last entry, then write ,plus the new data minus the initial [of the new data. Otherwise, it's your first array element, so just write your array normally.

如果您想向 JSON 文件添加另一个数组元素,如示例所示,请打开该文件并查找到最后。如果文件已有数据,则向后查找一个字节以覆盖]后面的最后一个条目,然后写入,加上新数据减去新数据的首字母[。否则,它是您的第一个数组元素,因此只需正常编写您的数组即可。

Sorry I don't know enough about PHP to post actual code, but I've done this in Obj-C and it's allowed me to avoid reading the whole file in first just to add onto the end:

抱歉,我对 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);
}

回答by Cristiana Chavez

Sample code I used to append additional JSON array to JSON file.

我用来将额外的 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);   

回答by Ramesh KC

/*
 * @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));
}

回答by Martin Mbae

I wrote this PHP code to add json to a json file. The code will enclose the entire file in square brackets and separate the code with commas.

我写了这段 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); 

}

    ?>

GoodLuck

祝你好运