如何使用PHP将JSON数据记录到文件?

时间:2016-06-18 01:43:39

标签: php json

这是我发现的代码。

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

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

2 个答案:

答案 0 :(得分:3)

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

<?php

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

如果要附加到文件,首先需要将文件读入数组,添加数组的较新部分然后再次对其进行编码,然后再写回文件朋友@ Rizier123描述。

答案 1 :(得分:1)

好的,我发现了一种更有效的方法。

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文件解码为数组。