Update json file in php

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.

Источник

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.)

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.

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 json file with .php?

I have a json file on my server that I would like to update using a php file. By update I mean put new key value pairs. Is it possible for anyone to point me to the right direction? A tutorial or an example perhapes? Thank you

Bring it into php, file_get_contents, decode it, json_decode, modify as needed, reencode, json_encode, save it back, file_put_contents. Google probably has functional examples.

2 Answers 2

 ['First entry'] ])); echo "Wrote 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 bytes", PHP_EOL; 

this kind of replaces all the data in my .json file. but I wanted to update my .json file. I mean like add new data while the old data would still be intact.

OK. you can just use an array in the JSON data, like this: $obj_data->events[] = ‘Next entry’; — assuming the «events» property is an array. I’ll update my answer with a sample.

No probs. Not very scalable this though — you might want to think about a database or something!! Good luck

The new sample for some reason does not work but if i remove «if(!file_exists(JSON_FILE)) < $int_bytes = file_put_contents(JSON_FILE, json_encode((object)[ 'events' =>[‘First entry’] ])); echo «Wrote bytes to new file», PHP_EOL; >» this then it does the job 🙂

Источник

How to update a json file with only new elements?

I recieve a json from another page with many elements, one of them is an id. What I want to do is create a new json with only the ids, so here is what I am doing: First, the json is decoded to store in server as files. It is stored in an array. From there I store all the ids in another array, this is the simplified version of what I’m doing:

$json_array = json_decode(file_get_contents('path/to/file.json')); foreach($json_array as $arr) < $ids[] = $arr['id']; >file_put_contents('ids.json', json_encode($ids)); 

So far it is doing what I want, I got a json with all the id’s. The problem is, my json file updates and only shows the last 50 items. So whenever this is called, I get the last 50 id’s. For example, if I got 50 items, then my json has id 1 to id 50, but if I got 60 items, it shows from id 10 to id 60, so the first 10 ids are replaced and gone. I would like to keep those first 10 ids, but still update with new ids and avoid duplicates. The problem is that in the example I gave, items 10 to 50 are the same, and only the last 10 are new. I’m not sure if this is possible. To be clear: My current json: id’s from 1 — 50. Update json: items 10 — 60 (the items from 10 to 50 are the same as before). What I would like my json to keep: id’s from 1 — 60, with no duplicates. (Keep this everytime there is an update, so if json has 100 — 150 items, my ids json would store ids from 1 to 150). I gave numbers as example to be more clear, it doesnt really update with 10 new items, it could be any random number. Oh and I’m working with Codeigniter, if that’s any help. Thanks for your help and time, I have googled everywhere for a solution, but I’m not exactly sure what to look for.

Источник

Читайте также:  Sum to number javascript
Оцените статью