douci1196 2011-03-22 16:37
浏览 38
已采纳

如何使用RecursiveDirectoryIterator循环引用当前目录名称,文件名和文件内容?

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?
        }
    }
  • 写回答

1条回答 默认 最新

  • dongxia2068 2011-03-22 17:25
    关注
    //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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。