【问题标题】:How do I record JSON data to file using PHP?如何使用 PHP 将 JSON 数据记录到文件中?
【发布时间】:2016-06-18 01:43:38
【问题描述】:

这是我想出来的代码。

<?php
$username = $_POST['username'];
$email = $_POST['email'];
$json = '{"username":"'.$username.'",'.'"email":"'.$email.'"}';
$file = fopen('token_data.json','w+');
fwrite($file, $json);
fclose($file);
?>

但这绝对不是正确的方法。

【问题讨论】:

  • 1) 将数据放入一个数组并使用json_encode() 将其编码为 JSON 2) 当您想要添加内容时,获取文件内容,对其进行解码并将您的数组添加到其中,然后然后在再次保存之前对其进行编码。
  • 是什么让你这么认为?你会如何改进它?提示:看看json_encode
  • 你遇到了什么错误?
  • 由于$_POST 一个数组,你可以用它直接转到JSON。
  • @JeffPuckettII 我没有收到错误,通过这种方式我无法将数据添加到文件中,我只是覆盖它。

标签: php json


【解决方案1】:

如果您的 $_POST 数组包含您需要的所有数据,您可以将其编码为 JSON 并写入文件:

<?php

    $json = json_encode($_POST);
    $file = fopen('token_data.json','w+');
    fwrite($file, $json);
    fclose($file);
?>

如果你想追加到文件,你需要先将文件读入一个数组,添加数组的较新部分然后在写回文件之前再次对其进行编码,就像我的朋友@Rizier123 描述。

【讨论】:

  • 正如@Rizier123 和我所描述的那样。你想让我为你写代码吗?
  • 请写,我不太明白把文件读入数组...
  • 我知道我不应该问@skygate,但这不是 Stack Overflow 的工作方式。我们在这里帮助您解决问题,而不是为您编写代码。我已经给你步骤了。使用fopen() 之类的内容读取文件。将 JSON 解码为带有 json_decode() 之类的数组。向数组中添加新数据,可能是array_push()。试一试,当您需要您编写的代码方面的帮助时回来。
【解决方案2】:

好的,我找到了一种更有效的方法。

Original Answer

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

无需将整个 JSON 文件解码为数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-04
    • 2011-12-15
    • 1970-01-01
    • 2015-02-07
    • 2020-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多