我有一个带有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"; }
}
您的list.txt
文件在每行末尾都有换行符。例如,你首先需要在$filename
中使用file_exists()
之前修剪它
<?php
$file = "list.txt";
$parts = new SplFileObject($file);
foreach ($parts as $filename) {
$fn = trim($filename);
if (file_exists($fn)) {
echo "The file $fn exists\n";
} else {
echo "The file $fn does not exist\n";
}
}
加载文件时尝试通过explode()函数将字符串分解为数组。然后,您将能够使用file_exist函数进行验证