PHP遍歷目錄檔案常用方法
- php語言
- 關注:7.34K次
導語:PHP遍歷目錄檔案常用方法有哪些,下面是小編給大家整理的PHP遍歷目錄檔案常用方法,大家可以參考閱讀,更多詳情請關注應屆畢業生考試網。
演算法1.簡短系
foreach(glob('*.*') as $filename)
{
echo 'Filename:'.$filename.;
}
演算法2.規矩系
if($handle = opendir('C:Inetpubwwwroottest')){
echo "Files:n";
while (false !== ($file = readdir($handle))){
echo "$filen";
}
closedir($handle);
}
演算法3.函式系
function tree($directory)
{
$mydir=dir($directory);
while($file=$mydir->read()){
if((is_dir("$directory/$file")) AND ($file!=".") AND ($file!=".."))
{
echo "$filen";
tree("$directory/$file");
} else
echo "$filen";
}
echo "n";
$mydir->close();
}
tree("C:Inetpubwwwroottest");
演算法4.函式系II
function listDir($dir){
if(is_dir($dir)){
if ($dh = opendir($dir)) {
while (($file= readdir($dh)) !== false){
if((is_dir($dir."/".$file)) && $file!="." && $file!=".."){
echo "檔名:",$file;
listDir($dir."/".$file."/");
} else{
if($file!="." && $file!=".."){
echo $file;
}
}
}
closedir($dh);
}
}
}
listDir("C:Inetpubwwwroottest");
演算法5.遞迴系
function file_list($dir,$pattern="")
{
$arr=array();
$dir_handle=opendir($dir);
if($dir_handle)
{
while(($file=readdir($dir_handle))!==false)
{
if($file==='.' || $file==='..')
{
continue;
}
$tmp=realpath($dir.'/'.$file);
if(is_dir($tmp))
{
$retArr=file_list($tmp,$pattern);
if(!emptyempty($retArr))
{
$arr[]=$retArr;
}
} else
{
if($pattern==="" || preg_match($pattern,$tmp))
{
$arr[]=$tmp;
}
}
}
closedir($dir_handle);
}
return $arr;
}
print_r(file_list("C:Inetpubwwwroottest"));
測試方法
我們採取在測試程式碼的頭部和尾部新增如下的內容來檢測執行時間,並測試5次取平均結果作為最終成績。
$stime=microtime(true);
//測試程式碼
//......
//......
$etime=microtime(true);
$total=($etime-$stime)*1000;
echo "{$total} Millisecond(s)";
測試結果:
演算法1
演算法1在瀏覽器能正確輸出所有專案,5次測驗耗費的時間分別是:
平均用時=3803.618621824 毫秒
演算法2
演算法2在瀏覽器也能正確輸出所有專案,但在開頭會給出“..”(上級目錄)的資訊。5次測驗耗費的時間分別是:
平均用時=381.0853481294 毫秒
演算法3
演算法3在瀏覽器能正確輸出所有專案,也仍會給出“..”(上級目錄)的資訊。5次測驗耗費的時間分別是:
平均用時=24299.2805485 毫秒
演算法4
演算法4和演算法3類似,在瀏覽器能正確輸出所有專案,5次測驗耗費的時間分別是:
平均用時=24020.66812516 毫秒
演算法5
演算法5曾一度讓我以為IIS又出問題了。雖說它在瀏覽器能正確輸出所有專案,但資料的結果預設為陣列。5次測驗耗費的`時間分別是:
平均用時=61411.31243706 毫秒
測試總結
根據測試結果,我們很容易得出下面的速度排名。
演算法2 > 演算法1 > 演算法4 > 演算法3 > 演算法5
為什麼演算法2要比其他演算法都高效一些呢?
實際上是因為演算法中只使用了php中內建用來讀取目錄內容的函式“readdir()” 。除了演算法1以外,其他演算法在引用readdir()的時候,為了彌補函式的先天不足,幹了很多其他的事情。
如果說,我們需要指定副檔名的列舉目錄內所有檔案的話。Rt推薦使用演算法1的模式,我們將程式碼寫成這樣就可以了。
foreach(glob('*.需要的副檔名') as $filename)
{
echo 'Filename:'.$filename.;
}
- 文章版權屬於文章作者所有,轉載請註明 https://xuezhezhai.com/zh-tw/jsj/php/o9g5em.html