Php 遍历文本文件并检查服务器上是否存在该文件
我有一个txt文件,其中包含40.000个文件路径和文件名,我需要检查它们是否存在 要检查单个文件,我使用以下代码:Php 遍历文本文件并检查服务器上是否存在该文件,php,loops,file-exists,splfileobject,Php,Loops,File Exists,Splfileobject,我有一个txt文件,其中包含40.000个文件路径和文件名,我需要检查它们是否存在 要检查单个文件,我使用以下代码: $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"; } 那代码行得
$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函数验证您的
list.txt
文件在每行末尾都有一个换行符。例如,在文件\u exists()
中使用$filename
之前,首先需要将其修剪掉
<?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函数进行验证