我在将 json 重新编码回其格式时遇到了一些问题。我试图实现的是,在 .json 文件上传上,对其进行修改以满足某些标准。
问题是当我尝试修改文件上的图像 src 并将其编码回 json 时,但是 foreach 循环中的数组正确打印出来,新文件是在没有任何内容的情况下生成的!
很高兴你能给我一点帮助
function prepareImages($file,$url,$article)
{
$string = file_get_contents($file);
$json = json_decode($string,true);
$value = array();
//$array = $json['elements'];
//$imgArray = array();
/* if(['type'] == "image")
{
array_push($json['elements']['src'],$array);
} */
foreach($json['elements'] as $value)
{
if($value['type'] == "image")
{
$arr = explode('''', $value['src']);
$count = count($arr);
$img = $arr[$count-1];
$src = $url.'res/'.$article.'/'.$img;
$value['src'] = $src;
//print_r($json);
}
//This prints all the values correctly
print_r($value);
}
$json = $value;
$string = json_encode($json);
file_put_contents($file,$string);
}
根据 json_encode() 文档,该函数转义正斜杠,请尝试这样做:
$value['src'] = str_replace('''/', '/', $src)