我需要只读取目录中的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>";
}
}
更优雅:
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
}
您可以通过筛选文件类型来完成此操作。。以下是示例代码。
<?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文件执行同样的操作。
此处更好地解释