分為兩個,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 . "nr";<br>
$curDir = $dirname . '/' . $fn;<br>
<br>
// echo "curDir = " . $curDir . "rn";<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>($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:'@.
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' .
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>
}*/<br>