如何用.php更新json文件?

时间:2015-02-25 00:26:58

标签: php json

我的服务器上有一个json文件,我想用php文件更新。通过更新我的意思是放置新的键值对。是否有人能指出我正确的方向?教程或示例perhapes?谢谢

2 个答案:

答案 0 :(得分:1)

这是一个简单的例子......

<?php

// Define the file here
define('JSON_FILE', '/tmp/data.json');

// Create the empty file
if(!file_exists(JSON_FILE)) {
    $int_bytes = file_put_contents(JSON_FILE, json_encode((object)[
        'events' => ['First entry']
    ]));
    echo "Wrote {$int_bytes} bytes to new file", PHP_EOL;
}

// Load and decode
$obj_data = json_decode(file_get_contents(JSON_FILE));

// Show the data after loading
print_r($obj_data);

// Set some data
$obj_data->awesome = true;
$obj_data->name = "tom";

// Add an event to the array
$obj_data->events[] = "Event at " . time();

// Show the data before saving
print_r($obj_data);

// Encode and save!
$int_bytes = file_put_contents(JSON_FILE, json_encode($obj_data));

echo "Wrote {$int_bytes} bytes", PHP_EOL;

答案 1 :(得分:0)

你会得到类似的东西:

    $yourFileContent = file_get_contents($pathToFileWithJson); //<-- but note that file should contain ONLY valid JSON without any other symbols
    //you can also add validation here if you managed to get something, etc...
    $yourFileContent = json_decode($yourFileContent,true);
    //then you can also add validation if you managed to parse json. if failled to parse, you can process it separately.
    $yourFileContent+=array('newKey'=>'newValue','newKey2'=>'newValue2'); //<--add keys if not exists (actual only for dictionaries)
    file_put_contents($pathToFileWithJson,json_encode($yourFileContent));