分为两个,1:不考虑json数据有空格
2:考虑json文件有空格<?php <br />
/*<br>
*time:2016年12月3日16:42:46<br>
*author:zhangchennyang<br>
*功能:json文件遍历压缩<br>
*<br>
*/<br>
<br>
header('content-type:text/html;charset=utf8');<br>
fRename('../json'); //使用该方法参数为文件夹目录<br>
function fRename($dirname)<br>
{<br>
if (!is_dir($dirname)) {<br>
echo "{$dirname}不是一个有效的目录!";<br>
exit();<br>
}<br>
$handle = opendir($dirname);<br>
while (($fn = readdir($handle)) !== false) {<br>
if ($fn != '.' && $fn != '..') {<br>
<br>
// echo "fn = " . $fn . "\n\r";<br>
$curDir = $dirname . '/' . $fn;<br>
<br>
// echo "curDir = " . $curDir . "\r\n";<br>
if (is_dir($curDir)) {<br>
fRename($curDir);<br>
} else {<br>
<br>
$path = pathinfo($curDir);<br>
//var_dump($curDir);<br>
$file_type=$path['extension'];<br>
if($file_type=='json'){<br>
$str=file_get_contents($curDir); //根据文件夹读取文本获得字符串<br>
$arr=json_decode($str,true); //转为数组<br>
<br>
<br>
$k_str=json_encode($arr);//数组转换为字符串<br>
$statu=file_put_contents($curDir,$k_str);<br>
<br>
if($statu){ //格式化成功<br>
$time=date('y-m-d h:i:s'); //执行时间<br>
$wenjian=$curDir;<br>
$ok_= 'file' . $wenjian . '---time:' . $time.'-'.PHP_EOL;<br>
file_put_contents('ok.txt',$ok_, FILE_APPEND);<br>
<br>
}else{<br>
$time=date('y-m-d h:i:s'); //执行时间<br>
$wenjian=$curDir;<br>
$error_info= 'file' . $wenjian . '---time:' . $time.'-'.PHP_EOL; <br>
file_put_contents('error.txt',$error_info, FILE_APPEND);<br>
}<br>
<br>
} <br>
}<br>
<br>
}<br>
<br>
}<br>
}<br>
<br>
<br>
<br>
//去掉空格等等字符串<br>
/*function trimall($str){<br>
$qian=array(" "," ","\t","\n","\r");<br>
$hou=array("","","","","");<br>
return str_replace($qian,$hou,$str); <br>
<br>
}*/