dongyu3967
2017-12-20 11:50
浏览 81
已采纳

迭代文本文件并检查服务器上是否存在文件

I have a txt file with 40.000 file paths with filenames that I need to check if they exist.

To check for a single file i use the following code:

$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";
}

That code works.

Now I want to iterate through the txt file, that contains one path per row

/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
...

I tried to iterate through the txt file with this code, but i get "file does not exist" for all files.

$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"; }      
}

图片转代码服务由CSDN问答提供 功能建议

我有一个带有40.000个文件路径的txt文件,文件名需要检查它们是否存在。

要检查单个文件,请使用以下代码:

  $ filename ='/ home / httpd / html / domain.com / htdocs /  car / 002.jpg'; 
if(file_exists($ filename)){
 echo“文件$ filename存在”; 
} else {
 echo“文件$ filename不存在”; 
} \  n   
 
 

该代码有效。

现在我想遍历txt文件,每行包含一个路径

 <代码> /home/httpd/html/domain.com/htdocs/car/002.jpg \ N /家/ httpd的/ HTML / domain.com / htdocs中/汽车/ 003.JPG \  n / 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“文件$ filename exists”  ;  } 
 else {echo“文件$ filename不存在”;  } 
} 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doulongdan2264 2017-12-20 12:01
    已采纳

    Your list.txt file has a newline at the end of each line. You first need to trim that off before using $filename in the file_exists() like this for example

    <?php
    $file = "list.txt";
    $parts = new SplFileObject($file);
    foreach ($parts as $filename) {
        $fn = trim($filename);
        if (file_exists($fn)) {
            echo "The file $fn exists
    ";
        } else {
            echo "The file $fn does not exist
    ";
        }
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dqyq88053 2017-12-20 11:54

    when you load a file try to break the string into array by explode() function. Then you will be able to validate with file_exist function

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题