我正在IMDB風格的網站上工作,我需要動態地查找電影的評論數量。評論存儲在名爲/moviefiles/moviename/review[*].txt
的文件夾中,其中[*]
是評論的編號。基本上我需要返回一個整數,那個目錄中有多少個這樣的文件。我該怎麼做呢?如何在PHP中統計目錄中的.txt文件數量?
謝謝。
我正在IMDB風格的網站上工作,我需要動態地查找電影的評論數量。評論存儲在名爲/moviefiles/moviename/review[*].txt
的文件夾中,其中[*]
是評論的編號。基本上我需要返回一個整數,那個目錄中有多少個這樣的文件。我該怎麼做呢?如何在PHP中統計目錄中的.txt文件數量?
謝謝。
看看在3210功能: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>
試試下面的代碼中的文本文件的數量要找到.txt文件數
$directory = '/var/www/ajaxform/';
$files = glob($directory . '*.txt');
if ($files !== false)
{
$filecount = count($files);
echo $filecount;
}
else
{
echo 0;
}
回報$ filecount;
使用PHP DirectoryIterator或FileSystemIterator:
$directory = new DirectoryIterator(__DIR__);
$num = 0;
foreach ($directory as $fileinfo) {
if ($fileinfo->isFile()) {
if($fileinfo->getExtension() == 'txt')
$num++;
}
}
這是一個非常簡單的代碼,效果很好。 :)
$files = glob('yourfolder/*.{txt}', GLOB_BRACE);
foreach($files as $file) {
your work
}