Change json file php

PHP JSON. Запись, чтение и редактирование JSON файла. Пишем полноценное приложение

php json

Привет. Здесь вы узнаете как работать с JSON в PHP. Мы напишем полноценное приложение по типу CRUD, которое уже делали, но в этот раз хранить данные в БД не будем, а запишем их и будем редактировать и удалять в JSON файле. Это уже полноценное программирование и реальный рабочий пример того, как делать запись в JSON файл. Но прежде прошу обратить ваше внимание, что с файлами мы уже работали и делали гостевую книгу. Теперь же вы сможете сделать такую же, но данные будут храниться в формате JSON вместо обычного текста и таким образом сможете сделать полноценную админку, где будете редактировать сообщения.

Телеграм-канал serblog.ru

Напишем некий задачник или TODO лист. Традиционно подключим Bootstrap для удобства и создадим таблицу, в которой будем выводить данные из JSON файла. В ней будет всего три поля: ID записи, сама запись и кнопки редактирования и удаления. Сделаем кнопку добавления записи через модальное окно.

Весь HTML здесь приводить не буду, он получился довольно массивный. Пример вы можете скачать по ссылке в конце статьи? а так же посмотреть видеоурок.

1 2 3 4 5 6 7 8 9 10 11 12
button class="btn btn-success mb-1" data-toggle="modal" data-target="#exampleModal">i class="fas fa-plus-circle">/i>/button> table class="table table-bordered"> thead class="table-dark"> tr> th scope="col">№/th> th scope="col">Задача/th> th scope="col">Действие/th> /tr> /thead> tbody> /tbody> /table>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

div class=«modal fade» id=«exampleModal» tabindex=«-1» role=«dialog» aria-labelledby=«exampleModalLabel» aria-hidden=«true»> div class=«modal-dialog» role=«document»> div class=«modal-content»> div class=«modal-header»> h5 class=«modal-title» id=«exampleModalLabel»>Добавить запись/h5> button type=«button» class=«close» data-dismiss=«modal» aria-label=«Close»> span aria-hidden=«true»>×/span> /button> /div> div class=«modal-body»> form action=«PHP_SELF«]);?>» method=»post»> div class=«input-group»> input type=«text» class=«form-control» name=«todo» /> /div> /form>/div> div class=«modal-footer»> button class=«btn btn-primary send» data-send=«1»>Создать/button> /div> /div> /div> /div>

А вот и сам PHP код, который делает всю магию:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
$todoName = htmlspecialchars($_POST['todo']); $todoName = trim($todoName); $jsonArray = []; //Если файл существует - получаем его содержимое if (file_exists('todo.json')){ $json = file_get_contents('todo.json'); $jsonArray = json_decode($json, true); } // Делаем запись в файл if ($todoName){ $jsonArray[] = $todoName; file_put_contents('todo.json', json_encode($jsonArray, JSON_FORCE_OBJECT)); header('Location: '. $_SERVER['HTTP_REFERER']); } // Удаление записи $key = @$_POST['todo_name']; if (isset($_POST['del'])){ unset($jsonArray[$key]); file_put_contents('todo.json', json_encode($jsonArray, JSON_FORCE_OBJECT)); header('Location: '. $_SERVER['HTTP_REFERER']); } // Редактирование if (isset($_POST['save'])){ $jsonArray[$key] = @$_POST['title']; file_put_contents('todo.json', json_encode($jsonArray, JSON_FORCE_OBJECT)); header('Location: '. $_SERVER['HTTP_REFERER']); }

Между открывающим и закрывающим тегом tbody в таблице вставляем цикл foreach:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57

< ?php foreach ($jsonArray as $key =>$todo): ?>

Читайте также:  Php socket get stream contents
echo $key;?>» tabindex=»-1″ role=»dialog» aria-labelledby=»exampleModalLabel» aria-hidden=»true»>
echo htmlspecialchars($_SERVER[«PHP_SELF»]);?>» method=»post»>
echo $key; ?/>«>

» style=»color: #000000; font-weight: bold;»>php echo $key;?>» tabindex=»-1″ role=»dialog» aria-labelledby=»exampleModalLabel» aria-hidden=»true»>

echo $todo; ?/>«>

hidden» name=»todo_name» value=» echo $key;?/>«>

—footer«>

< ?php foreach ($jsonArray as $key =>$todo): ?>

» tabindex=»-1″ role=»dialog» aria-labelledby=»exampleModalLabel» aria-hidden=»true»>

Источник

Add, Update, Delete and Read JSON Data/File in PHP

Hi! Today let’s see about JSON CRUD with PHP. Yep! Manipulating json data — add, update (edit), delete and read json file using php script. JSON is everywhere these days. With increasing popularity of APIs it’s a must for a developer to know how to read, parse and manipulate json data. If you wonder what the connection between API and JSON is, almost all modern APIs lean towards REST and they provide response as JSON. (In KodingMadeSimple.com I have covered json topics a lot earlier and you can visit our JSON Tutorials section to learn more about working with JSON format.)

Читайте также:  All text in document javascript

php add edit delete read json file

JSON is the string notation of JavaScript object. It takes up simple to complex forms and stores data as (key, value) pairs.

This is the example of a json file.

results.json

Now let me show you how to read and parse through above json file using php.

Read JSON File in PHP:

To read json file with php, you must first get the json data stored in the file, decode json and finally parse through the array or object.

For that you’ll need two php functions — one is file_get_contents() and the other is json_decode() .

If you know the specific key name, then you can simply access it like this,

Note: The function json_decode() decodes the given json string into an array or object. For example the statement json_decode($data, true); in above code will return associative array. You can ignore the second parameter ‘true’ to make it return as an object.

Add to JSON File in PHP:

To add additional records to json file you have to simply append it to the end of file. Here let’s see an example for adding new data. The following php snippet takes up a json file, decode it, add extra records and again encode to json and save it into a new file.

4, 'Name'=>'Jeff Darwin', 'Sports'=>'Cricket'); // encode json and save to file file_put_contents('results_new.json', json_encode($json_arr)); ?>

results_new.json

Update JSON File PHP:

As for updating json file you can either modify single value or in bulk. Here’s an example for modifying value for a specific json attribute.

 $value) < if ($value['Code'] == '2') < $json_arr[$key]['Sports'] = "Foot Ball"; >> // encode array to json and save to file file_put_contents('results_new.json', json_encode($json_arr)); ?>

Here’s what the script does.

  • Load results.json file to a variable
  • Decode json data to array
  • Loop through the array and check if key ‘Code’ is ‘2’
  • And edit the corresponding ‘Sports’ value to ‘Foot Ball’

results_new.json

Delete JSON Data from File:

JSON deletion is little complex since it is easy to mess up doing the process. You must be clear what you need to delete first, a specific key pair from all rows or a complete row.

For example this php script will delete entire record from json containing key ‘Code’ as ‘2’.

 $value) < if ($value['Code'] == "2") < $arr_index[] = $key; >> // delete data foreach ($arr_index as $i) < unset($json_arr[$i]); >// rebase array $json_arr = array_values($json_arr); // encode array to json and save to file file_put_contents('results_new.json', json_encode($json_arr)); ?>

And this is the file we get after deletion.

The deletion script uses two foreach loops. The first one is for determining the array index we need to delete from json.

Читайте также:  Php fpm errors nginx

And the second is what actually deletes from array using unset() function.

Finally it rebases the array, encode it to json and store it in a new file.

Likewise you can add, edit, delete and read json file in php. It’s easy to mess up with json and so many newbies confuses json and actual javascript object. JSON can get complex if it uses nested structure and you’ll have real trouble manipulating it. Only constant practice will get you there and it’s easy to master it in my opinion.

I hope you like this tutorial. Please don’t forget to share it with your friends.

1 comment:

// unset($json_arr[$i]); will remove wrong row

// i suggest modify like this ——————

Contact Form

Subscribe

You May Also Like

Like Us on Facebook

Categories

Affiliate Disclosure: This website is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to amazon(.com, .in etc) and any other website that may be affiliated with Amazon Service LLC Associates Program.

Kodingmadesimple.com uses affiliate links to online merchants and receives compensation for referred sales of some or all mentioned products but does not affect prices of the product. All prices displayed on this site are subject to change without notice. Although we do our best to keep all links up to date and valid on a daily basis, we cannot guarantee the accuracy of links and special offers displayed.

Источник

How to Update/Edit JSON File in PHP?

In this tutorial, you will learn How to Update Json File in php. if you want to see example of How to Update Json Data in php then you are a right place. we will help you to give example of PHP Read and Write Json File. Here you will learn PHP Modify Json File.

Here, I will give the following example of how to update/edit json file in php program, we will use The file_get_contents() this function reads a file into a string, The json_decode() function is use to JSON encoded string and convert into a PHP variable and file_put_contents() function is use to save file.

Example: update/edit json file

I simply created data.json file with content as like below:

[

<

«id»: 1,

«name»: «Hardik Savani»,

«email»: «hardik@gmail.com»

>,

<

«id»: 2,

«name»: «Jaydeep Pathar»,

«email»: «jaydeep@gmail.com»

>,

<

«id»: 3,

«name»: «Vivek Pathar»,

«email»: «vivek@gmail.com»

>

]

//get file

$datas = file_get_contents(‘data.json’);

//Decode the JSON data into a PHP array.

$datasDecoded = json_decode($datas, true);

// Create Array to json file for Add data

$datasDecoded[] = [«id» => 4, «name» => «Mehul Bagda», «email» => «mehul@gmail.com»];

$datasDecoded[] = [«id» => 5, «name» => «Nikhil Thummer», «email» => «nikhil@gmail.com»];

//Encode the array back into a JSON string.

$json = json_encode($datasDecoded);

//Save the file.

file_put_contents(‘result.json’, $json);

?>

[

<

«id»:1,

«name»:»Hardik Savani»,

«email»:»hardik@gmail.com»

>,

<

«id»:2,

«name»:»Jaydeep Pathar»,

«email»:»jaydeep@gmail.com»

>,

<

«id»:3,

«name»:»Vivek Pathar»,

«email»:»vivek@gmail.com»

>,

<

«id»:4,

«name»:»Mehul Bagda»,

«email»:»mehul@gmail.com»

>,

<

«id»:5,

«name»:»Nikhil Thummer»,

«email»:»nikhil@gmail.com»

>

]

✌️ Like this article? Follow me on Twitter and Facebook. You can also subscribe to RSS Feed.

You might also like.

Источник

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