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

ben*_*e89 13 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"
    }
]
Run Code Online (Sandbox Code Playgroud)

这是我的PHP代码:

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

$fp = fopen('results.json', 'a');
fwrite($fp, json_encode($data));
fclose($fp);
Run Code Online (Sandbox Code Playgroud)

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

Tim*_*Tim 35

$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);
Run Code Online (Sandbox Code Playgroud)

  • 这不会花费更长的时间吗?当你有一个巨大的JSON文件时,难道不是很荒谬吗?我正在处理大量数据. (21认同)

小智 24

这已经采用了上面的例子并将其移至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);
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*c B 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));
Run Code Online (Sandbox Code Playgroud)

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