为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

交互式爱情 2023-12-19 10:36:41
首先,我声明变量来获取文件夹,并将文件放入数组中。见下文  $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 40Unable to open file!
查看完整描述

1 回答

?
子衿沉夜

TA贡献1828条经验 获得超3个赞

您缺少文件的完整路径。当您扫描目录时,您使用 $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

}

在仅调用文件名的情况下,脚本会尝试在执行脚本的同一目录中打开文件。


查看完整回答
反对 回复 2023-12-19
  • 1 回答
  • 0 关注
  • 50 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信