Ответ 1
$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);
У меня есть этот файл .json:
[
{
"id": 1,
"title": "Ben\\ First Blog Post",
"content": "This is the content"
},
{
"id": 2,
"title": "Ben\\ 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 с [
и {
, возможно ли это?
$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);
Это взято выше, например, и переместило его на 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);
}
Вы разрушаете свои 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
, что является синтаксически неправильным.
Если вы хотите добавить другой элемент массива в файл 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);
}
Пример кода, который я использовал для добавления дополнительного массива 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);
/*
* @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));
}
Я написал этот код 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);
}
?>
Удачи