How to Add/Append Data to JSON File using PHP

Append data to a json file with php

I might recommend that you restructure your file to be a txt file which is a collection of json strings — all of which are separately written on each line. Demo) Output: Secondly, I don’t support the notion of building this json file if there is any way that you can avoid it.

Append data to a .JSON file with PHP

$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); 

This has taken the above c example and moved it over to php. This will jump to the end of the file and add the new data in without reading all the file into memory.

// 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); > 

You’re ruining your json data by blindly appending text to it. JSON is not a format that can be manipulated like this.

Читайте также:  Basic File Upload

You’ll have to load your json text, decode it, manipulate the resulting data structure, then re-encode/save it.

Let’s say you’ve got [1,2,3] stored in your file. Your code could turn that into [1,2,3]4 , which is syntactically wrong.

Append data to a .JSON file with PHP, If you want to add another array element to a JSON file as your example shows, open the file and seek

Append Data to JSON File using PHP

Append json in file using php form

Append json in file using php form. How to store form data in a json file using php | PHP Duration: 13:08

Append data to top of the JSON file using PHP form

At beggining you have [1] then you insert [2] and after $array_data[] = $extra; goes to [1][2] and the you reverse array [2][1]. At this moment when you insert a new value you have [2][1][3] and the after reversing [3][1][2] the solution would be reversing before insert extra:

  $_REQUEST['name'], 'author' => $_REQUEST["author"], 'category'=> $_REQUEST["category"], 'url' => $_REQUEST["url"] ); echo $extra['name']; $array_data = array_reverse($array_data); $array_data[] = $extra; $array_data = array_reverse($array_data); $final_data = json_encode($array_data); if(file_put_contents('wallpaper.json', $final_data)) < $message = ""; > > ?> 

to run I used to pass parameters:

http://localhost/test.php?name=4&author=4&category=4&url=4 
$posted[] = $_POST; $current_data = file_get_contents('wallpaper.json'); $decoded = json_decode($current_data,true); //You merge together posted array values with the current array //that is in the current file (after decoding the json) //$posted is first part of the array because you start to merge from that //array $new_arr = array_merge($posted, $decoded); //Encode the new array into JSON and save it $encoded_json = json_encode($new_arr,); file_put_contents('wallpaper.json', $encoded_json); 

First, don’t push the $_POST data into its own subarray. It is already in the correct structure to call array_unshift() directly on it. In other words, you don’t need to index it — unshift will apply the 0 key for you.

$fileContents = '[,]'; $array = json_decode($fileContents, true); $_POST = [ 'name' => 'C1', 'author' => 'C2', 'category' => 'C3', 'url' => 'C4', ]; array_unshift($array, $_POST); echo json_encode($array); 

Secondly, I don’t support the notion of building this json file if there is any way that you can avoid it. I mean, as you your file size increases, your server will have to work harder and harder and harder to parse the json, manipulate it, re-encode it every time you want to make a change.

I might recommend that you restructure your file to be a txt file which is a collection of json strings — all of which are separately written on each line. This way you don’t have to unpack and repack your data every time, you just prepend the new json string to the file and walk away. *Caveat, this will fail if the data that you are storing contains newline characters — I don’t know if your project might receive such data.

p.s. If you are not a ultra-purist developer and your incoming data is as tame as it looks from your post, you can hack at the json string and lighten the workload like this:

$newJson = json_encode($_POST); if ($fileContents) < $fileContents = substr_replace($fileContents, $newJson . ',', 1, 0); >else < $fileContent = '[' . $newJson . ']'; >echo $fileContents; 

How to append in JSON file at specific position using PHP

I’ve this code in php for appending data array in last postion. But I want to append data array in 0 position.

 $_POST['id'], 'name' => $_POST['name'], 'age' => $_POST['age'], 'address' => $_POST['address'], 'dob' => $_POST['dob'], ); $array_data[] = $extra; $final_data = json_encode($array_data); if(file_put_contents('myfile.json', $final_data)) < $message = ""; > ?> 

Append data to json file php Code Example, data[] = $_POST[‘data’]; $inp = file_get_contents(‘results.json’); $tempArray = json_decode($inp); array_push($tempArray, $data);

How to Append JSON File in PHP?

'b','media_category'=>'v','media_info'=>'c','media_location'=>'x','media_artist'=>'z'); array_push($temp_array->upload->image, $upload_info); file_put_contents('upload.json', json_encode($temp_array)); > else < $upload_info = array(); $upload_info['upload']['image'][] = array('media_name'=>'b','media_category'=>'v','media_info'=>'c','media_location'=>'x','media_artist'=>'z'); $json = json_encode($upload_info); $file = "upload.json"; file_put_contents($file, $json); > ?> 

This one just work for you!

$json_data = json_decode(file_get_contents('data.txt'), true); for ($i = 0, $len = count($json_data); $i < $len; ++$i) < $json_data[$i]['num'] = (string) ($i + 1); >file_put_contents('data.txt', json_encode($json_data)); 

example from here: Parsing JSON file with PHP

Php — how to add item to the json file formatted array, $data=$_POST[‘myusernamer’]; $inp = file_get_contents(‘7players.json’); $tempArray = json_decode($inp); array_push($tempArray, $data);

Источник

How to Add Data to JSON File in PHP

add data to json file in php

I’ve used Bootstrap in this tutorial which is a CSS framework and is included in the downloadable of this tutorial, but if you want, you may download Bootstrap using this link .

Also, please take note that I’ll be using members.json that I have included in the downloadable of this tutorial.

Displaying a JSON Data

Next, we display the existing data in our JSON file and create the add/append form as well. Create a new record, name it as index.php and paste the codes below.

       

Add/Append Data to JSON File

?>
"; > ?>
ID Firstname Lastname Address Gender
".$row->id." ".$row->firstname." ".$row->lastname." ".$row->address." ".$row->gender."

Creating an Append Script

Lastly, we create a script that adds data to our JSON file. Please create a new record, name it as add.php and paste the codes below.

 $_POST['id'], 'firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname'], 'address' => $_POST['address'], 'gender' => $_POST['gender'] ); //append the POST data $data_array[] = $input; //return to json and put contents to our file $data_array = json_encode($data_array, JSON_PRETTY_PRINT); file_put_contents('members.json', $data_array); $_SESSION['message'] = 'Data successfully appended'; > else < $_SESSION['message'] = 'Fill up add form first'; >header('location:index.php'); ?>

That ends this tutorial. Happy Coding!

Источник

Дописать в файл json и прочесть его php?

Добрый день!
Немного запутался в JSON на PHP
Стоит задача записывать даныые в тектовый файл либо в json файл данные, но не просто записывать а дописывать новыми данными, свого рода бд. так на данный момент удобнее, понимаю что лучше использовать бд, но хочеться сперва использовать все таки файл.

$datetime = date("Y-m-d H:i:s"); $date = date("Y-m-d"); $time = date("H:i:s"); $array = [ 'Дата' => $datetime, 'День' => $date, 'Время' => $time, ]; $json = json_encode($array, JSON_UNESCAPED_UNICODE); $filename = 'trunk_hook_json.json'; file_put_contents($filename,$json,FILE_APPEND | LOCK_EX); echo $json; exit();

Данные успешно записываються в файл

Затем читаю таким образом

$Json = file_get_contents('trunk_hook_json.json'); $array = json_decode($Json); var_dump($array);

Результат выводит если запись ф файле одна, если две то выводит null
Подскажите что не так делаю?

Простой 1 комментарий

FanatPHP

json — не потоковый формат. его нельзя читать и писать по кусочку
только целиком
поэтому если надо добавлять в конец, по степени предпочтительности в данном случае будет
база данных (она не такая страшная, как кажется)
CSV
джейсон (который надо переписывать с нуля)

в теории конечно можно совместить второй и третий вариант, но я бы не стал этого делать

Immortal_pony

file_put_contents($filename,$json,FILE_APPEND | LOCK_EX);
$payload = file_exists($filename) ? ",]" : "[]"; $fileHandler = fopen($filename, "c"); fseek($fileHandler, -1, SEEK_END); fwrite($fileHandler, $payload); fclose($fileHandler);

FanatPHP

Immortal_pony

FanatPHP Это ты ещё не видел как я xml-конфиги средствами mysql парсил. И не от хорошей жизни, поверь ))

Immortal_pony, если вновь записываемые json настолько независимы от предыдущих, что мы предыдущие даже не смотрим, зачем тогда их объединять в один json? Почему бы не писать их отдельными строками? Каждую строку при этом можно будет обрабатывать отдельно. Собственно как это и делается в системах логирования. Смысл расширять дозаписыванием со странными телодвижениями, когда при чтении придется читать все скопом?
И когда автор запустит свою шайтан-машину и она насоздает записей, через некоторое время он опять придет с новой задачей: не перезаписывая весь файл удалить из json несколько первых объектов.

В общем то все супер, есть небольшая помарка ,если файл был пустой начинается с , < но это вообще не проблема, поставил [< и все ,остальные записи полетели как надо!
Маленький вопрос, в файле все идет в одну строку, не принциписально конечно, можно каждую запись заставить с новой строки писать без потери функционала?

SteepNET, можно, очевидно просто добавьте символ новой строки при записи.
Только зачем? Что будет дальше? Комментарии в json?
Это все превращается, как написал FanatPHP, в «ковыряться грязными ногами в джейсоне».

Vitsliputsli, Вы правы, может быть я делаю не верно, правильнее было бы просто добавлять данныые в БД и оттуда спокойно брать, да но это тоже опыт, за полгода лог накапливает в себе всего 5 мб данных,но статистику из него брать нужно..

SteepNET, бд не панацея, которая спасёт от всего и вся. Если речь про 10Мб в год, то действительно стоит задуматься о том, так ли необходима бд. Тут проще прочитать и записать файл целиком. Опять же, есть sqlite.
Либо хранить в json отдельные события лога, а писать-читать построчно. А потрошение json и запись отдельных кусков не лучшая идея. Но мало того, что сама идея плохая, она ничего полезного не даёт, если сравнить с записью построчно.

Immortal_pony

Vitsliputsli Я не знаю конкретный случай автора, но запись в json может понадобиться для интеграции каких-либо внешних, систем, например. Или для поиска по логам есть классные консольные утилиты, с которыми удобно работать, а не эти ваши grep верхом на sed или cut

SteepNET Товарищи, возражающие против json хотят склонить вас не к записи в БД, а к записи логов в CSV-формате — в таком виде строки будут по-настоящему независимыми и не надо будет шаманить со скобками в попытках создания валидного json’а. Бонусом — строки будут максимально человекочитаемыми. Для этого можно воcпосльзоваться fputcsv и fgetcsv
Что же касается json’а и новых строк, это можно сделать так:

$eol = PHP_EOL; $payload = file_exists($filename) ? ",]" : "[]";

Immortal_pony, В двойне спасибо! Да ,json как то привычней, хотя от метода с csv тоже не отказался бы.
На самом деле я в поиске решения, удобного решения для всех, но прежде всего собираюсь обрабатывать этот лог через php, делать выборки и фильтрацию данных, уже даже есть определенные успехи, не знаю как поведет себя все это когда файл начнет быть пухлым ,содержащим 10-ки тысяч записей, но никто не мешает мне начать писать в новый или сделать лимитирование файла скажем посуточно..

Immortal_pony

SteepNET Из моего опыта, до 50к записей фильтрация и сортировка будут отрабатывать в пределах 1сек на не шибко резвом сервере.
Если записей будет больше, то следует всё же задуматься о смене хранилища.

Immortal_pony, для интеграции с внешними системами лучше подготовить API, а не подстраивать свое хранилище под них и позволять им напрямую лазить в него.
Товарищи склоняющие к CSV вместо json исходят из того, что так им привычнее. Только вот сейчас 2022 и формировать отдельные строчки в логе как json это нормальная, обычная практика, и как софт уже может формировать в таком виде логи, так и системы организации логов, тот же logstash могут читать их.
А учитывая, что автор пишет построчно, а при чтении готов читать только часть, ту которая последняя после ротации файла, то на мой взгляд писать лог отдельными строками внутри которых json — самый оптимальный вариант.

Источник

Оцените статью