php scandir() not showing files - only showing directories

那年仲夏 提交于 2019-12-23 21:42:40

问题


I have a directory structure as follows:

/files
/files/001
/files/001/addfile.php
/files/002
/files/002/deletefile.php
/files/003
/files/003/viewfile.php

My script:

error_reporting(E_ALL);
$directory      = 'files';
$files      = scandir($directory);

$xml = new DOMDocument('1.0', 'UTF-8');
$xmlFiles = $xml->appendChild($xml->createElement('FILES'));
if(is_dir($directory)) {
    print_r($files);
}
/*foreach($files as $file => $key) {
    if($file == '.' || $file == '..') { continue; }
    echo '$file: '.$file;
    if(is_dir("$directory/$file")) {
        $xmlDir->appendChild($xml->createElement($file));
    }
    else {
        $xmlFiles->appendChild($xml->createElement('FILE', $file));
    }
}*/
echo $xml->saveXML();

My problem: The print_r($files) outputs:

Array ( [0] => . [1] => .. [2] => 001 [3] => 002 [4] => 003 )

How come scandir only outputs the directories and not the files?

TIA, Nate


回答1:


your files are in these directories, and scandir shows just content of specified path, but without any recurrency, so all is correct.




回答2:


Scandir does not work recursively. It only scans the path input into it.

Scandir Recurrsive function to scan deeper into the file system




回答3:


you can use RecursiveIteratorIterator for get directory with sub directory listing

Here is how to empty a directory using iterator:

<?php
function empty_dir($dir) {
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),
                                             RecursiveIteratorIterator::CHILD_FIRST);
   foreach ($iterator as $path) {
     if ($path->isDir()) {
        // do something with directory
        //    rmdir($dir);
     } else {
       //doo something with files 
       // unlink($path->__toString());
     }
   }
  //    rmdir($dir);
}
?>


来源:https://stackoverflow.com/questions/13557502/php-scandir-not-showing-files-only-showing-directories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!