如何将JSON数据存储在平面文件数据库中?

时间:2013-02-21 19:20:01

标签: php database json flat-file

我需要将一些数据存储在JSON文件中。我知道如何使用json_encode,但我找不到有关如何将编码数据写入外部文件的任何信息。这里有一些打印出编码数据的代码,但是如何在单独的JSON文件中写入数据呢?

<?php
$array1 = array('key1' => "data1",
        'key2' => "data2",
        'key3' => "data3",
        'key4' => "data4",
        'key5' => "data5");

echo json_encode($array1);
?>

2 个答案:

答案 0 :(得分:1)

file_put_contents('array1.json', json_encode($array1));

答案 1 :(得分:0)

使用fwrite(...)

来自DOC:     

// Let's make sure the file exists and is writable first.
if (is_writable($filename)) {

    // In our example we're opening $filename in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $somecontent will go when we fwrite() it.
    if (!$handle = fopen($filename, 'a')) {
         echo "Cannot open file ($filename)";
         exit;
    }

    // Write $somecontent to our opened file.
    if (fwrite($handle, $somecontent) === FALSE) {
        echo "Cannot write to file ($filename)";
        exit;
    }

    echo "Success, wrote ($somecontent) to file ($filename)";

    fclose($handle);

} else {
    echo "The file $filename is not writable";
}
?>

或者只使用file_put_contents(...)

file_put_contents($filname, $data);