[英]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.