有人可以帮我在json文件中提供str_replace值吗?我的代码在替换字符串上运行良好,但是在json中的值上却不起作用。
在所有json文件中都能很好地将“旧”正确替换为“新”:
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);
}
但是当我需要替换时"min_order":""
,"min_order":"1"
它不起作用。我不能直接替换""
为"1"
,因为json中有许多其他值。
我测试了这段代码,但是没有用:
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);
}
有人可以帮我解决这个问题吗?
先感谢您。吉里
一旦你做 $file_contents = file_get_contents($path_to_file);
然后,您应该使用json_decode($file_contents);
将json字符串转换为数组或对象,
然后通过替换需要替换的键的值来操纵数组/对象,
然后在修改后的数组上使用json_encode();
以将数组/对象转换回JSON格式
最后 file_put_contents($path_to_file,$file_contents);
在JSON中可以在json格式上使用str_replace,但不建议这样做,也不可行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句