Reputation: 43
could somebody help me with str_replace value in json file, please? My code working well on replace string, but it dosnt working on value in json.
Working well to replace correctly "old" with "new" in all json files:
foreach(glob('*.json') as $path_to_file) {
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace('old','new',$file_contents);
file_put_contents($path_to_file,$file_contents);
}
But when I need replace "min_order":""
with "min_order":"1"
it doesn't work. I can not replace ""
with "1"
directly, because I have in json many other values.
I tested this code, but it didn't work:
foreach(glob('*.json') as $path_to_file) {
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace('"min_order":""','"min_order":"1"',$file_contents);
file_put_contents($path_to_file,$file_contents);
}
Can somebody help me with this issue please?
Thank you in advance. Jiri
Upvotes: 1
Views: 3070
Reputation: 6601
Once you do $file_contents = file_get_contents($path_to_file);
you should then use json_decode($file_contents);
to convert the json string to array or object,
then manipulate the array/object by replacing THERE the value of the key you need to replace,
and then use on that modified array json_encode();
to convert the array/object back to JSON format
and finally file_put_contents($path_to_file,$file_contents);
Using str_replace on json format is possible within JSON but is not advisable, nor is practical.
Upvotes: 3