簡體   English   中英

如何計算PHP目錄中.txt文件的數量?

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

首先,使用glob()獲取文件列表數組,然后使用count()獲取數組長度,該數組長度為文件計數。

簡化代碼:

$txtFileCount = count( glob('/moviefiles/moviename/review*.txt') );

這是一個非常簡單的代碼,效果很好。 :)

$files = glob('yourfolder/*.{txt}', GLOB_BRACE);
foreach($files as $file) {
    your work
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM