开发者

How to reference the current directory name, filename and file contents with RecursiveDirectoryIterator loop?

开发者 https://www.devze.com 2023-02-18 20:17 出处:网络
In the script below, I\'m attempting to iterate over the folders and files inside of the $base folder. I expect it to contain a single level of child folders, each containing a number of .txt files (a

In the script below, I'm attempting to iterate over the folders and files inside of the $base folder. I expect it to contain a single level of child folders, each containing a number of .txt files (and no subfolders).

I'm just needing to understand how to reference the elements in comments below...

Any help much appreciated. I'm really close to wrapping this up :-)

$base = dirname(__FILE__).'/widgets/';
$rdi = new RecursiveDirectoryIterator($base);
foreach(new RecursiveIteratorIterator($rdi) as $files_widgets) 
    {
     if ($files_widgets->isFile()) 
         {
            $file_name_widget = $files_widgets->getFilename(); //what is the filename of the current el?
            $widget_text = file_get_contents(???); //How do I reference the file here to obtain its contents?
            $sidebar_id = $files_widgets->getBasename(); //what is the file's parent directory name?
        }
   开发者_如何学C }


//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.

0

精彩评论

暂无评论...
验证码 换一张
取 消