【问题标题】:Iterate through text file and check if file exist on server遍历文本文件并检查服务器上是否存在文件
【发布时间】: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


【解决方案1】:

您的list.txt 文件在每行末尾都有一个换行符。在file_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";
    }
}

【讨论】:

    【解决方案2】:

    当您加载文件时,请尝试通过explode() 函数将字符串分解为数组。 然后您将能够使用 file_exist 函数进行验证

    【讨论】:

      猜你喜欢
      • 2018-10-31
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 2012-05-15
      • 2012-10-01
      • 2012-06-13
      • 2014-06-27
      相关资源
      最近更新 更多