'Change a value of json variable in a php file
Hi i have a php file that contain json value. I want to change the value of json variable .But i am not sure how t do that .
my-file.php
<?
$json_data;
$json_varible = json_decode('{"pen_color":"red","book_size":"large","book_color":"red", etc etc }', true);
....
?>
Now I want to change the value of pen_color to green . Please note there are many parameters in json_decode
So i write following
//read the entire string
$str=file_get_contents('my-file.php');
$old_value= "red";
$new_value = "green";
//replace something in the file string - this is a VERY simple example
$str=str_replace($old_value, $new_value,$str);
file_put_contents('my-file.php', $str);
I am sure that this code is wrong. Please help me to solve the issue. I want t change pen_color to green
Solution 1:[1]
May be it is that you want
$json_variable = json_decode('{"pen_color":"red","book_size":"large","book_color":"red"}', true);
$json_variable['pen_color'] = 'green';
$json_value = json_encode($json_variable);
file_put_contents('my-file.php', $json_value );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
