Добавить данные в файл .JSON с помощью PHP - PullRequest
12 голосов
/ 26 октября 2011

У меня есть этот файл .json:

[
    {
        "id": 1,
        "title": "Ben\\'s First Blog Post",
        "content": "This is the content"
    },
    {
        "id": 2,
        "title": "Ben\\'s Second Blog Post",
        "content": "This is the content"
    }
]

Это мой код PHP:

<?php
$data[] = $_POST['data'];

$fp = fopen('results.json', 'a');
fwrite($fp, json_encode($data));
fclose($fp);

Дело в том, что я не совсем уверен, как этого добиться. Я собираюсь вызывать этот код выше каждый раз при отправке формы, поэтому мне нужно увеличить идентификатор и сохранить действительную структуру JSON с [ и {, возможно ли это?

Ответы [ 7 ]

33 голосов
/ 26 октября 2011
$data[] = $_POST['data'];

$inp = file_get_contents('results.json');
$tempArray = json_decode($inp);
array_push($tempArray, $data);
$jsonData = json_encode($tempArray);
file_put_contents('results.json', $jsonData);
22 голосов
/ 12 февраля 2014

Это взял вышеупомянутый пример c и переместил его в php.Это перейдет к концу файла и добавит новые данные без чтения всего файла в память.

// 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);
}
14 голосов
/ 26 октября 2011

Вы портите данные JSON, слепо добавляя к ним текст. JSON - это не тот формат, которым можно манипулировать следующим образом.

Вам придется загрузить текст json, декодировать его, манипулировать получающейся структурой данных, а затем перекодировать / сохранить его.

<?php

$json = file_get_contents('results.json');
$data = json_decode($json);
$data[] = $_POST['data'];
file_put_contents('results.json', json_encode($data));

Допустим, у вас [1,2,3] хранится в вашем файле. Ваш код может превратить это в [1,2,3]4, что синтаксически неправильно.

4 голосов
/ 02 марта 2013

Если вы хотите добавить другой элемент массива в файл JSON, как показано в примере, откройте файл и выполните поиск до конца.Если в файле уже есть данные, ищите в обратном направлении один байт, чтобы перезаписать ] после последней записи, затем запишите , плюс новые данные минус начальные [ новых данных.В противном случае, это ваш первый элемент массива, поэтому просто пишите свой массив нормально.

Извините, я недостаточно знаю о PHP, чтобы публиковать реальный код, но я сделал это в Obj-C, и это позволило мнене читайте сначала весь файл, просто добавьте в конец:

NSArray *array = @[myDictionary];
NSData *data = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];
FILE *fp = fopen(fname, "r+");
if (NULL == fp)
    fp = fopen(fname, "w+");
if (fp) {
    fseek(fp, 0L, SEEK_END);
    if (ftell(fp) > 0) {
        fseek(fp, -1L, SEEK_END);
        fwrite(",", 1, 1, fp);
        fwrite([data bytes] + 1, [data length] - 1, 1, fp);
    }
    else
        fwrite([data bytes], [data length], 1, fp);
    fclose(fp);
}
3 голосов
/ 17 ноября 2015

Пример кода, который я использовал для добавления дополнительного массива JSON в файл JSON.

$additionalArray = array(
    'id' => $id,
    'title' => $title,
    'content' => $content
);

//open or read json data
$data_results = file_get_contents('results.json');
$tempArray = json_decode($data_results);

//append additional json to json file
$tempArray[] = $additionalArray ;
$jsonData = json_encode($tempArray);

file_put_contents('results.json', $jsonData);   
0 голосов
/ 04 апреля 2019

Я написал этот код PHP, чтобы добавить json в файл json.Код будет заключать весь файл в квадратные скобки и отделять код запятыми.

<?php

//This is the data you want to add
//I  am getting it from another file
$callbackResponse = file_get_contents('datasource.json');

//File to save or append the response to
$logFile = "results44.json";


//If the above file does not exist, add a '[' then 
//paste the json response then close with a ']'


if (!file_exists($logFile)) {
  $log = fopen($logFile, "a");
  fwrite($log, '['.$callbackResponse.']');
  fclose($log);                      
}


//If the above file exists but is empty, add a '[' then 
//paste the json response then close with a ']'

else if ( filesize( $logFile) == 0 )
{
     $log = fopen($logFile, "a");
  fwrite($log, '['.$callbackResponse.']');
  fclose($log);  
}


//If the above file exists and contains some json contents, remove the last ']' and 
//replace it with a ',' then paste the json response then close with a ']'

else {

$fh = fopen($logFile, 'r+') or die("can't open file");
$stat = fstat($fh);
ftruncate($fh, $stat['size']-1);
fclose($fh); 

$log = fopen($logFile, "a");
  fwrite($log, ','.$callbackResponse. ']');
  fclose($log); 

}

    ?>

GoodLuck

0 голосов
/ 19 мая 2018
/*
 * @var temp 
 * Stores the value of info.json file
 */
$temp=file_get_contents('info.json');

/*
 * @var temp
 * Stores the decodeed value of json as an array
 */
$temp= json_decode($temp,TRUE);

//Push the information in temp array
$temp[]=$information;

// Show what new data going to be written
echo '<pre>';
print_r($temp);

//Write the content in info.json file
file_put_contents('info.json', json_encode($temp));
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...