How can I retrieve the full directory tree using SPL?
By default, the RecursiveIteratorIterator
will use LEAVES_ONLY
for the second argument to __construct
. This means it will return files only. If you want to include files and directories (at least that's what I'd consider a full directory tree), you'd have to do:
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST
);
and then you can foreach
over it. If you want to return the directory tree instead of outputting it, you can store it in an array, e.g.
foreach ($iterator as $fileObject) {
$files[] = $fileObject;
// or if you only want the filenames
$files[] = $fileObject->getPathname();
}
You can also create the array of $fileObjects
without the foreach
by doing:
$files[] = iterator_to_array($iterator);
If you only want directories returned, foreach
over the $iterator
like this:
foreach ($iterator as $fileObject) {
if ($fileObject->isDir()) {
$files[] = $fileObject;
}
}
php get full path of file in a folder
<?php
$path = dirname(__FILE__);
$objects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST
);
foreach ($objects as $file => $object) {
$basename = $object->getBasename();
if ($basename == '.' or $basename == '..') {
continue;
}
if ($object->isDir()) {
continue;
}
$fileData[] = $object->getPathname();
}
var_export($fileData);
List all the files and folders in a Directory with PHP recursive function
Get all the files and folders in a directory, don't call function when you have .
or ..
.
Your code :
<?php
function getDirContents($dir, &$results = array()) {
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (!is_dir($path)) {
$results[] = $path;
} else if ($value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
var_dump(getDirContents('/xampp/htdocs/WORK'));
Output (example) :
array (size=12)
0 => string '/xampp/htdocs/WORK/iframe.html' (length=30)
1 => string '/xampp/htdocs/WORK/index.html' (length=29)
2 => string '/xampp/htdocs/WORK/js' (length=21)
3 => string '/xampp/htdocs/WORK/js/btwn.js' (length=29)
4 => string '/xampp/htdocs/WORK/js/qunit' (length=27)
5 => string '/xampp/htdocs/WORK/js/qunit/qunit.css' (length=37)
6 => string '/xampp/htdocs/WORK/js/qunit/qunit.js' (length=36)
7 => string '/xampp/htdocs/WORK/js/unit-test.js' (length=34)
8 => string '/xampp/htdocs/WORK/xxxxx.js' (length=30)
9 => string '/xampp/htdocs/WORK/plane.png' (length=28)
10 => string '/xampp/htdocs/WORK/qunit.html' (length=29)
11 => string '/xampp/htdocs/WORK/styles.less' (length=30)
is_dir doesn't recognize directories. Why?
is_dir($dir . '/' . $subdir)
Sorting files per directory using SPL's DirectoryTreeIterator
Well, I'm not sure where you got that class from, but it's doing some pretty messed up things (including a few bugs to say the least). And while it uses SPL, it's not an SPL class.
Now, I'm not 100% sure what you mean by "sort", but assuming you're talking about a natural sort, why not just flatten an array, and then sort it?
$it = new RecursiveTreeIterator(
new RecrusiveDirectoryIterator($dir),
RecursiveTreeIterator::BYPASS_KEY,
CachingIterator::CALL_TOSTRING
);
$files = iterator_to_array($it);
natsort($files);
echo implode("\n", $files);
or
$it = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($dir),
RecursiveIteratorIterator::SELF_FIRST
);
$files = iterator_to_array($it);
$files = array_map(function($file) { return (string) $file; }, $files);
natsort($files);
echo implode("\n", $files);
Edit: Based on your edit, here's how I would solve it:
function BuildTree($it, $separator = ' ', $level = '') {
$results = array();
foreach ($it as $file) {
if (in_array($file->getBasename(), array('.', '..'))) {
continue;
}
$tmp = $level . $file->getBaseName();
if ($it->hasChildren()) {
$newLevel = $level . $separator;
$tmp .= "\n" . BuildTree($it->getChildren(), $separator, $newLevel);
}
$results[] = $tmp;
}
natsort($results);
return implode("\n", $results);
};
$it = new RecursiveDirectoryIterator($dir);
$tree = BuildTree($it);
It's a pretty simple recursive parser, and does the natural sort on each level.
How to reference the current directory name, filename and file contents with RecursiveDirectoryIterator loop?
//How do I reference the file here to obtain its contents?
$widget_text = file_get_contents(???);
$files_widgets
is a SplFileInfo, so you have a few options to get the contents of the file.
The easiest way is to use file_get_contents
, just like you are now. You can concatenate together the path and the filename:
$filename = $files_widgets->getPathname() . '/' . $files_widgets->getFilename();
$widget_text = file_get_contents($filename);
If you want to do something funny, you can also use openFile
to get a SplFileObject. Annoyingly, SplFileObject doesn't have a quick way to get all of the file contents, so we have to build a loop:
$fo = $files_widgets->openFile('r');
$widget_text = '';
foreach($fo as $line)
$widget_text .= $line;
unset($fo);
This is a bit more verbose, as we have to loop over the SplFileObject to get the contents line-by-line. While this is an option, it'll be easier for you just to use file_get_contents
.
php write subdirectories' contents into separate text files
Most likely you are not filtering out the directories .
and ..
.
$maindir=opendir('A');
if (!$maindir) die('Cant open directory A');
while (true) {
$dir=readdir($maindir);
if (!$dir) break;
if ($dir=='.') continue;
if ($dir=='..') continue;
if (!is_dir("A/$dir")) continue;
$subdir=opendir("A/$dir");
if (!$subdir) continue;
$fd=fopen("$dir.log",'wb');
if (!$fd) continue;
while (true) {
$file=readdir($subdir);
if (!$file) break;
if (!is_file($file)) continue;
fwrite($fd,file_get_contents("A/$dir/$file");
}
fclose($fd);
}
how to display folders and sub folders from dir in PHP
Collect the directory names in an array instead of echo
ing them directly. Use sort
on the array and a foreach
-loop to print the list.
So instead of echo ("$dirname/");
you would use $dirnames[] = $dirname;
(make $dirnames global and initialize it before your first call of "ListFolder"). Then after the recursive run of "ListFolder", you'd execute sort($dirnames);
and then something like this for the output:
foreach ($dirnames as $dirname)
{
echo $dirname . '<br />';
}
PHP recursive directory path
Try to use RecursiveIteratorIterator in combination with RecursiveDirectoryIterator
$path = realpath('/path/you/want/to/search/in');
$objects = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($path),
RecursiveIteratorIterator::SELF_FIRST);
foreach($objects as $name => $object){
if($object->getFilename() === 'work.txt') {
echo $object->getPathname();
}
}
Additional reading:
- http://www.phpro.org/tutorials/Introduction-to-SPL.html
Listing all the folders subfolders and files in a directory using php
function listFolderFiles($dir){
$ffs = scandir($dir);
unset($ffs[array_search('.', $ffs, true)]);
unset($ffs[array_search('..', $ffs, true)]);
// prevent empty ordered elements
if (count($ffs) < 1)
return;
echo '<ol>';
foreach($ffs as $ff){
echo '<li>'.$ff;
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff);
echo '</li>';
}
echo '</ol>';
}
listFolderFiles('Main Dir');
Related Topics
How to Handle Error for Duplicate Entries
What Causes: "Notice: Uninitialized String Offset" to Appear
Utf-8 Encoded HTML Pages Show Questions Marks Instead of Characters
PHP Date Format /Date(1365004652303-0500)/
Jquery Mobile: How to Correctly Submit Form Data
What's the Best Practice to Set HTML Attribute via PHP
How to Check If a Video Exists on Youtube, Using PHP
How to Fetch All in Assoc Array from a Prepared Statement
Sqlstate[Hy000] [1045] Access Denied for User 'Username'@'Localhost' Using Cakephp
Pre-Declare All Private/Local Variables
Is Making Asynchronous Http Requests Possible with PHP
Getting Time Difference Between Two Times in PHP
How to Loop Through $_Files Array