猿问

有没有办法用 scandir 循环遍历文件夹?我在循环时遇到问题

首先,我声明变量来获取文件夹,并将文件放入数组中。见下文


  $DOCROOT = $_SERVER['DOCUMENT_ROOT'];

  $dir    = $DOCROOT . '/php/pagamentos/resources/pagamentos';

  echo ($dir);

  $folder = array_diff(scandir($dir), array('.', '..'));

我有以下数组要循环:


array(4) {

  [2]=>

  string(33) "BMEPS_out22002508200201095005.txt"

  [3]=>

  string(33) "BMEPS_out22002508200204112009.txt"

  [4]=>

  string(33) "BMEPS_out22002508200204125012.txt"

  [5]=>

  string(33) "BMEPS_out22002508200205063000.txt"

}

然后我开始使用以下代码循环数组


foreach ($folder as $file) {


    $fp = fopen($file, "r") or die("Unable to open file!");


    echo $file;



    fclose($fp);

}

但毕竟我收到以下错误:


Warning: fopen(BMEPS_out22002508200204112009.txt): failed to open stream: No such file or directory in /var/www/html/php/pagamentos/index.php on line 40

Unable to open file!


交互式爱情
浏览 88回答 1
1回答

子衿沉夜

您缺少文件的完整路径。当您扫描目录时,您使用 $dir = $DOCROOT . '/php/pagamentos/resources/pagamentos'; 但当您调用 fopen 时,您只需使用文件名。您必须提供完整路径。例如:foreach ($folder as $file) {    $fullPath = $DOCROOT . '/php/pagamentos/resources/pagamentos/' . $file;    //or    $fullPath = $dir . '/' . $file;    //now you use $fullPath instead just $file}在仅调用文件名的情况下,脚本会尝试在执行脚本的同一目录中打开文件。
随时随地看视频慕课网APP

相关分类

Html5
我要回答