-2

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

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

echo json_encode($array1);
?>
4

2 回答 2

1
file_put_contents('array1.json', json_encode($array1));
于 2013-02-21T19:22:30.413 回答
0

利用fwrite(...)

来自文档:

// 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);
于 2013-02-21T19:22:25.983 回答