2017-02-16 100 views
1

我正在IMDB風格的網站上工作,我需要動態地查找電影的評論數量。評論存儲在名爲/moviefiles/moviename/review[*].txt的文件夾中,其中[*]是評論的編號。基本上我需要返回一個整數,那個目錄中有多少個這樣的文件。我該怎麼做呢?如何在PHP中統計目錄中的.txt文件數量?

謝謝。

回答

0

您可以使用此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> 
2

試試下面的代碼中的文本文件的數量要找到.txt文件數

$directory = '/var/www/ajaxform/'; 
$files = glob($directory . '*.txt'); 

if ($files !== false) 
{ 
    $filecount = count($files); 
    echo $filecount; 
} 
else 
{ 
    echo 0; 
} 

回報$ filecount;

1

使用PHP DirectoryIterator或FileSystemIterator:

$directory = new DirectoryIterator(__DIR__); 
$num = 0; 
foreach ($directory as $fileinfo) { 
    if ($fileinfo->isFile()) { 
     if($fileinfo->getExtension() == 'txt') 
      $num++; 
    } 
} 
0

首先,使用glob()獲取文件列表數組,然後使用count()得到數組長度,數組的長度是文件數。

簡化代碼:

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

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

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