php把json文件格式化压缩成一行
项目需要,把格式化好的json文件去掉所有空格和换行,压缩成最小
就有了一下代码
<?php
$src_path = "./out/cli/json/";
$dst_path = "./compress/";
$files = glob($src_path . "*.json");
foreach($files as $file){
$in_file = $file;
// echo "in file: " . $in_file . "\n";
$text = file_get_contents($in_file);
$return = compress($text);
$out_file = str_replace($src_path, $dst_path, $file);
// echo "out file: " . $out_file . "\n";
file_put_contents($out_file, $return);
}
function compress($text)
{
return preg_replace("/(\r\n|\n|\r|\t)/i", '', $text);
}
?>
原来的json内容
{"data_get_from_sheets" : "[活跃宝箱]",
"data_get_length" : 4,
"data_get" : {
"1":{"index":1,"activity":25,"rewards":[[3,20],[1,10000]]},
"2":{"index":2,"activity":50,"rewards":[[3,30],[10401,2]]},
"3":{"index":3,"activity":75,"rewards":[[3,50],[37001,1]]},
"4":{"index":4,"activity":100,"rewards":[[3,100],[1,50000]]}
},
"data_sign_info_from_sheets" : "[通用活动报名]",
"data_sign_info_length" : 4,
"data_sign_info" : {
"1":{"id":1,"desc":"<font color=#d95014>冠军赛</font>马上开始!谁将登上冠军宝座,参与比赛和趣味竞猜可活动丰厚奖励哦~","items":[50012,1,8,29905],"time":10,"cancel":"取消","ok":"前往参与"},
"2":{"id":2,"desc":"<font color=#d95014>冠军赛</font>已经开始啦,正在进行竞猜阶段。是否前往参与竞猜?","items":[50012,1,8,29905],"time":10,"cancel":"取消","ok":"前往参与"},
"3":{"id":3,"desc":"<font color=#d95014>众神战场</font>马上开始啦,正在进行报名阶段,快来参与强者之间的较量吧!","items":[50603,8,10030,30302,2],"time":10,"cancel":"取消","ok":"前往报名"},
"4":{"id":4,"desc":"<font color=#d95014>众神战场</font>正在进行中,大量奖励等你来拿,是否进入?","items":[50603,8,10030,30302,2],"time":10,"cancel":"取消","ok":"进入战场"}
}
}
压缩后变成
{"data_get_from_sheets":"[活跃宝箱]","data_get_length":4,"data_get":{"1":{"index":1,"activity":25,"rewards":[[3,20],[1,10000]]},"2":{"index":2,"activity":50,"rewards":[[3,30],[10401,2]]},"3":{"index":3,"activity":75,"rewards":[[3,50],[37001,1]]},"4":{"index":4,"activity":100,"rewards":[[3,100],[1,50000]]}},"data_sign_info_from_sheets":"[通用活动报名]","data_sign_info_length":4,"data_sign_info":{"1":{"id":1,"desc":"<font color=#d95014>冠军赛</font>马上开始!谁将登上冠军宝座,参与比赛和趣味竞猜可活动丰厚奖励哦~","items":[50012,1,8,29905],"time":10,"cancel":"取消","ok":"前往参与"},"2":{"id":2,"desc":"<font color=#d95014>冠军赛</font>已经开始啦,正在进行竞猜阶段。是否前往参与竞猜?","items":[50012,1,8,29905],"time":10,"cancel":"取消","ok":"前往参与"},"3":{"id":3,"desc":"<font color=#d95014>众神战场</font>马上开始啦,正在进行报名阶段,快来参与强者之间的较量吧!","items":[50603,8,10030,30302,2],"time":10,"cancel":"取消","ok":"前往报名"},"4":{"id":4,"desc":"<font color=#d95014>众神战场</font>正在进行中,大量奖励等你来拿,是否进入?","items":[50603,8,10030,30302,2],"time":10,"cancel":"取消","ok":"进入战场"}}}
搞掂.