我使用php dir()函数从目录获取文件,并通过它循环。即使文件存在,php dir函数也会返回null
$d = dir('path');
while($file = $d->read()) {
/* code here */
}
但这返回false,并给出
上的空
调用成员函数read()方法,但该目录是否存在以及文件在那里。
此外,是否有任何替代我的上述代码?
我使用php dir()函数从目录获取文件,并通过它循环。即使文件存在,php dir函数也会返回null
$d = dir('path');
while($file = $d->read()) {
/* code here */
}
但这返回false,并给出
上的空
调用成员函数read()方法,但该目录是否存在以及文件在那里。
此外,是否有任何替代我的上述代码?
如果你看看到documentation您将看到:
返回目录的实例,或NULL以错误的参数,或 FALSE在另一个错误的情况。
所以Call to member function read() on null
意味着你有一个错误(我认为这是failed to open dir: No such file or directory in...
)。
您可以使用file_exists和is_dir来检查给定的路径是否是目录以及它是否真的存在。
例子:
<?php
...
if (file_exists($path) && is_dir($path)) {
$d = dir($path);
while($file = $d->read()) {
/* code here */
}
}
尝试使用此:
if ($handle = opendir('/path/to/files')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";
/* This is the correct way to loop over the directory. */
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
/* This is the WRONG way to loop over the directory. */
while ($entry = readdir($handle)) {
echo "$entry\n";
}
closedir($handle);
}
你可以试试这个:
$dir = new DirectoryIterator(dirname('path'));
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
var_dump($fileinfo->getFilename());
}
}
来源:PHP script to loop through all of the files in a directory?
如有检查您的文件路径的路径是正确的。那么请试试这个代码,这可能会帮助你。由于
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>
是路径的绝对路径?相对路径?相对于哪里? –
使用'is_dir(path);'函数 – Jer