【发布时间】:2018-06-02 23:27:35
【问题描述】:
我有一个包含 40.000 个文件路径的 txt 文件,我需要检查它们是否存在。
要检查单个文件,我使用以下代码:
$filename='/home/httpd/html/domain.com/htdocs/car/002.jpg';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
该代码有效。
现在我想遍历 txt 文件,每行包含一个路径
/home/httpd/html/domain.com/htdocs/car/002.jpg
/home/httpd/html/domain.com/htdocs/car/003.jpg
/home/httpd/html/domain.com/htdocs/car/004.jpg
...
我尝试使用此代码遍历 txt 文件,但我得到所有文件的“文件不存在”。
$file = "list.txt";
$parts = new SplFileObject($file);
foreach ($parts as $filename) {
if (file_exists($filename)) { echo "The file $filename exists"; }
else { echo "The file $filename does not exist"; }
}
【问题讨论】:
-
也许你在文件名后面附加了换行符?
-
当您加载文件时,请尝试通过explode() 函数将字符串分解为数组。然后您将能够使用 file_exist 函数进行验证
标签: php loops file-exists splfileobject