PHP 从目录中获取文件列表(在 Moodle 中)
我想打开一个目录并读取里面的所有文件并将它们放入一个数组中,到目前为止我已经:
$imagesdir = $CFG->dataroot.'/1/themeimages/';
这给了我该目录的路径,下一步是什么?
I want to open a directory and read all the files inside and put them into an array
, so far I have:
$imagesdir = $CFG->dataroot.'/1/themeimages/';
Which gives me the path to the directory, whats the next step?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
由于从您的标签列表中我假设您正在使用 Moodle,因此您可以简单地使用:
该函数包含在 moodlelib.php 中。
从文档中读取:
有关可选参数的更多信息,请参阅官方文档。
filelib.php 中还提供了读取文件内容的函数。
Since from your tag list I assume you're using Moodle, you can simply use the:
The function is contained in moodlelib.php.
Reading from the doc:
Please refer to the official doc for more information about the optional parameters.
Functions for reading content of files are also available in filelib.php.
解决方案是使用
opendir
+readdir
+linedir
(引用第一页的示例) :Another solution would be to use [the `[DirectoryIterator` class][4] ; quoting the example from][4] the `__construct` page :
Of course, in each case, instead of just echoing or dumping the name of the file, you'd have to put it into an array.
这意味着在循环之前初始化数组:
并且,在循环内部,使用类似于这两行之一的内容,具体取决于您选择的解决方案:
A solution would be to use
opendir
+readdir
+closedir
(quoting an example from the first page) :Another solution would be to use [the `[DirectoryIterator` class][4] ; quoting the example from][4] the `__construct` page :
Of course, in each case, instead of just echoing or dumping the name of the file, you'd have to put it into an array.
This would mean initializing the array before the loop :
And, inside the loop, use something like one of those two lines, depending on which solution you choose :
只需使用内置函数scandir:
所以你可以这样使用它:
当然你也可以使用 DirectoryIterator,但这要简单得多。
您还可以剥离点文件:
Just use the built in function scandir:
So you would use it like this:
Of course you can use DirectoryIterator too, but this is much simplier.
You can also strip dot files:
对于更加面向对象的方法,请使用 DirectoryIterator 类。
For a more OO approach use the DirectoryIterator class.
如果您稍后还需要过滤器,这是最短的解决方案:
php 自动排除
.
和..
如果您不需要所有文件,您也可以指定自己的掩码,如上
*.*
php 还会自动为您创建
$files
数组。最后一行也可以是:
here's the shortest solution if you also need a filter later on:
php automatically excludes
.
and..
you can also specify your own mask if you don't need ALL files, as shown in above
*.*
php also automatically creates the
$files
array for you.the last line can also be: