這個類的主要作用,迭代的讀取文件,因爲路徑存在中文,所以必須轉碼,
同時轉碼後,由於windows下的路徑分隔符,會對編碼後的路徑進行轉義,所以必須先對路徑名進行轉換
<?php
class Dir
{
private $fileList=array();
public function __construct($path)
{
$this->readFileList($path);
}
function readFileList($path)
{
$path=$this->transPathSep($path);
$encode=mb_detect_encoding($path, array('GB2312','GBK','UTF-8','BIG5','LATIN1'));
$path=mb_convert_encoding($path, 'GB2312', $encode);
//用於路徑讀取時用UTF編碼會失敗,所以先轉成GB2312
if ($fd=opendir($path))
{
while($fileName=readdir($fd))
{
//如果不是當前目錄和上級目錄
if($fileName !="." && $fileName !="..")
{
//如果是一個文件
if(is_file($path.'/'.$fileName))
{
$extName=pathinfo($path."/".$fileName)["extension"];
if(strtolower($extName)=='txt')
{
//上面把路徑轉成了GB2312,這裏再轉換會UTF-8編碼
$temp=mb_convert_encoding($path.'/'.$fileName, 'UTF-8', $encode);
$groupName=$this->groupFile($temp);
$this->fileList[$groupName][]=$temp;
}
}
//如果是一個目錄,則繼續遞歸讀取
else if(is_dir($path.'/'.$fileName))
{
$this->readFileList($path.'/'.$fileName);
}
}
}
}
@closedir($fd);
}
public function getFileList()
{
return $this->fileList;
}
//提取單詞分類,比如從A-Z
private function groupFile($filename)
{
$pos=strripos($filename, '/');
$word=strtolower(substr($filename, $pos+1, 1));
return $word;
}
//轉換window環境下路徑的默認分隔符\爲PHP識別更好的/
//因爲路徑名中包含漢字時,必須轉換爲gb2312時,php才能識別
//而在轉換爲gb2312後,如果路徑名是以windows下的\分隔的,則被轉換爲gb2312的中文會被轉義
//最後就會導致讀取對應的路徑失敗
//******所以在{路徑名}中包含中文時,一定要先轉換路徑分隔符,然後轉換爲gb2312編碼
private function transPathSep($path)
{
$system=$_SERVER["SERVER_SOFTWARE"];
$pat="#\((.*?)\)#";
$sysVer=null;
if(preg_match($pat,$system,$match))
{
$sysVer=$match[1];
}
else
{
die("匹配系統類型失敗<br />");
}
if(strtolower($sysVer)=="win32")
{
$realPath=str_replace("\\","/",$path);
return $realPath;
}
}
}
/*
$dir=new Dir('E:\CodeEdit\php\ciba\TXT格式的牛津電子詞典\牛津電子詞典');
$list=$dir->getFileList();
echo "<pre>";
print_r($list);
echo "</pre>"; */
?>