如何使用 RecursiveDirectoryIterator 循环引用当前目录名、文件名和文件内容?
在下面的脚本中,我尝试迭代 $base 文件夹内的文件夹和文件。我希望它包含单级子文件夹,每个子文件夹包含多个 .txt 文件(并且没有子文件夹)。
我只需要了解如何引用下面评论中的元素...
非常感谢任何帮助。我真的快要结束了:-)
$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?
}
}
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?
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$files_widgets
是一个 SplFileInfo,所以您有几个选项来获取文件的内容。最简单的方法是使用
file_get_contents
,就像您现在一样。您可以将路径和文件名连接在一起:如果您想做一些有趣的事情,您还可以使用
openFile
获取 SplFileObject.令人烦恼的是,SplFileObject 没有快速获取所有文件内容的方法,因此我们必须构建一个循环:这有点冗长,因为我们必须循环遍历 SplFileObject 才能逐行获取内容。虽然这是一个选项,但使用
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: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: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
.