[英]How to count number of .txt files in a directory in PHP?
我正在使用IMDB風格的網站,並且需要動態查找電影的評論數量。 評論存儲在名為/moviefiles/moviename/review[*].txt
的文件夾中,其中[*]
是評論的編號。 基本上,我需要以整數形式返回該目錄中存在的文件數量。 我該怎么做呢?
謝謝。
使用php DirectoryIterator或FileSystemIterator:
$directory = new DirectoryIterator(__DIR__);
$num = 0;
foreach ($directory as $fileinfo) {
if ($fileinfo->isFile()) {
if($fileinfo->getExtension() == 'txt')
$num++;
}
}
看看glob()
函數: http : //php.net/manual/de/function.glob.php
然后,您可以使用sizeof()
來計算有多少個文件。
您可以使用此php代碼獲取文件夾中文本文件的數量
<div id="header">
<?php
// integer starts at 0 before counting
$i = 0;
$dir = 'folder-path';
if ($handle = opendir($dir)) {
while (($file = readdir($handle)) !== false){
if (!in_array($file, array('.', '..')) && !is_dir($dir.$file))
{
$temp = explode(".",$file);
if($temp[1]=="txt")
$i++;
}
}
}
// prints out how many were in the directory
echo "There were $i files";
?>
</div>
這是一個非常簡單的代碼,效果很好。 :)
$files = glob('yourfolder/*.{txt}', GLOB_BRACE);
foreach($files as $file) {
your work
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.