2

我只需要读取目录中的 pdf 文件,然后读取每个文件的文件名,然后我将使用文件名重命名一些 txt 文件。我试过只使用eregi 功能。但它似乎无法阅读我需要的所有内容。如何读好它们?这是我的代码:

$savePath   ='D:/dir/';
$dir       = opendir($savePath);
$filename  = array();

while ($filename = readdir($dir)) {
if (eregi("\.pdf",$filename)){
    $read = strtok ($filename,"."); //get the filenames

//to rename some txt files using the filenames that I get before
//$testfile is text files that I've read before
    $testfile = "$read.txt";
    $file = fopen($testfile,"r") or die ('cannot open file');

    if (filesize($testfile)==0){} 
    else{
        $text = fread($file,55024);
        fclose($file);
        echo "</br>"; echo "</br>";         
    }
}
4

2 回答 2

4

更优雅:

foreach (glob("D:/dir/*.pdf") as $filename) {
    // do something with $filename
}

仅获取文件名:

foreach (glob("D:/dir/*.pdf") as $filename) {
    $filename = basename($filename);
    // do something with $filename
}
于 2012-07-24T05:48:38.537 回答
1

您可以通过过滤文件类型来执行此操作。以下是示例代码。

<?php 

// directory path can be either absolute or relative 
$dirPath = '.'; 

// open the specified directory and check if it's opened successfully 
if ($handle = opendir($dirPath)) { 

   // keep reading the directory entries 'til the end 
   $i=0; 
   while (false !== ($file = readdir($handle))) { 
   $i++; 

      // just skip the reference to current and parent directory 
      if (eregi("\.jpg",$file) || eregi("\.gif",$file) || eregi("\.png",$file)){ 
         if (is_dir("$dirPath/$file")) { 
            // found a directory, do something with it? 
            echo " [$file]<br>"; 
         } else { 
            // found an ordinary file 
            echo $i."- $file<br>"; 
         } 
      } 
   } 

   // ALWAYS remember to close what you opened 
   closedir($handle); 
}  

?>

以上演示了与图像相关的文件类型,您可以对 .PDF 文件执行相同的操作。

在这里更好地解释

于 2012-07-24T05:44:32.757 回答