”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 PHP 中从目录中检索文件名?

如何在 PHP 中从目录中检索文件名?

发布于2024-11-07
浏览:282

How to Retrieve Filenames from a Directory in PHP?

从 PHP 中的目录中检索文件

如何在 PHP 中访问目录中的文件名?事实证明,确定正确的命令具有挑战性。这个问题旨在为寻求类似解决方案的个人提供帮助。

PHP提供了几种从目录获取文件列表的方法:

DirectoryIterator(推荐)

此类允许对目录中的文件进行迭代:

foreach (new DirectoryIterator('.') as $file) {
    if($file->isDot()) continue;
    print $file->getFilename() . '
'; }

scandir

此函数检索目录中的文件和目录数组:

$files = scandir('.');
foreach($files as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '
'; }

readdir 和 opendir

此函数组合提供对目录句柄的访问:

if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if($file == '.' || $file == '..') continue;
        print $file . '
'; } closedir($handle); }

glob

此函数对于基于模式匹配文件很有用:

foreach (glob("*") as $file) {
    if($file == '.' || $file == '..') continue;
    print $file . '
'; }

附加说明

glob 允许使用模式进行更复杂的文件匹配,例如文本文件的 ''.txt' 或 'image_ ' 对于以前缀 'image_' 开头的文件。

版本声明 本文转载于:1729248137如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3