Jump to content

Recommended Posts

how can i get a list of filename and filepaths with the extension '.png' in the following directory structure, advanced solution should allow further files and directories to be added at any point in the tree:

/*

- folder

  - test1.png

  - test2.png

  - untitled.txt

  - subfolder

    - test3.png

    - untitled1.txt

*/

Link to comment
https://forums.phpfreaks.com/topic/205401-directory-tree/
Share on other sites

Below is the recursive function. Please note it can be memory overhead. 

 

this is only to get the filename you can modify it for the filepath also.

 

function getDirectoryTree( $outerDir ){
    $dirs = array_diff( scandir( $outerDir ), Array( ".", ".." ) );
    $dir_array = Array();
    foreach( $dirs as $d ){
        if( is_dir($outerDir."/".$d) ) $dir_array[ $d ] = getDirectoryTree( $outerDir."/".$d );
        else{
		$path_info = pathinfo($d);
		if($path_info['extension'] == 'png'){
			$dir_array[ $d ] = $d;
		}
	}
    }
    return $dir_array;
} 

$dir = getDirectoryTree("C://wamp/www/answers");
echo "<pre>";
print_r($dir);

Link to comment
https://forums.phpfreaks.com/topic/205401-directory-tree/#findComment-1074907
Share on other sites

$iterator = new RecursiveDirectoryIterator( new DirectoryIterator( 'path/to/directory' ) );
while ($iterator->valid()) {
    if ($iterator->isDot()) continue;
    
    echo $iterator->key(), "<br>\n";
}

 

Play with it and modify (extend) to suit your needs.

Link to comment
https://forums.phpfreaks.com/topic/205401-directory-tree/#findComment-1075139
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.