php - How str_replace value in json?
Get the solution ↓↓↓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
Answer
Solution:
Once you do$file_contents = file_get_contents($path_to_file);
you should then usejson_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 arrayjson_encode();
to convert the array/object back to JSON format
and finallyfile_put_contents($path_to_file,$file_contents);
Using str_replace on json format is possible within JSON but is not advisable, nor is practical.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the metadata storage is not up to date, please run the sync-metadata-storage command to fix this issue.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.