Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update/edit a JSON file using PHP [closed]

Tags:

json

php

Here is my JSON

[    {       "activity_code":"1",       "activity_name":"FOOTBALL"    },    {       "activity_code":"2",       "activity_name":"CRICKET"    } ] 

I need to update {"activity_code":"1","activity_name":"FOOTBALL"} to {"activity_code":"1","activity_name":"TENNIS"} based on activity_code

How can I achieve this in PHP?

like image 453
user475464 Avatar asked Jul 23 '13 09:07

user475464


People also ask

How do I make a JSON file editable?

Procedure. In the Enterprise Explorer view, right-click your . json file or other file type that contains JSON code and select Open With > JSON Editor. You can compress JSON strings so that the strings display on one line with white space removed between JSON elements.

Can we update JSON?

You can use json_mergepatch in an UPDATE statement, to update the documents in a JSON column.


1 Answers

First, you need to decode it :

$jsonString = file_get_contents('jsonFile.json'); $data = json_decode($jsonString, true); 

Then change the data :

$data[0]['activity_name'] = "TENNIS"; // or if you want to change all entries with activity_code "1" foreach ($data as $key => $entry) {     if ($entry['activity_code'] == '1') {         $data[$key]['activity_name'] = "TENNIS";     } } 

Then re-encode it and save it back in the file:

$newJsonString = json_encode($data); file_put_contents('jsonFile.json', $newJsonString); 
like image 173
Brewal Avatar answered Sep 24 '22 08:09

Brewal