只读pdf文件并在目录中获取该pdf文件的文件名

时间:2012-07-24 05:41:06

标签: php

我只需要读取目录中的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>";         
    }
}

2 个答案:

答案 0 :(得分:3)

更优雅:

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
}

答案 1 :(得分: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文件执行相同操作。

更好地解释here