遍历文件夹下所有文件,一般可以使用opendir 与 readdir 方法来遍历。
例子:找出指定目录下的所有php文件(不搜寻子文件夹),代码如下:
<code><span><span><?php </span><span>$path</span> = dirname(<span>__FILE__</span>); <span>$result</span> = traversing(<span>$path</span>); print_r(<span>$result</span>); <span><span>function</span><span>traversing</span><span>(<span>$path</span>)</span>{</span><span>$result</span> = <span>array</span>(); <span>if</span>(<span>$handle</span> = opendir(<span>$path</span>)){ <span>while</span>(<span>$file</span>=readdir(<span>$handle</span>)){ <span>if</span>(<span>$file</span>!=<span>'.'</span> && <span>$file</span>!=<span>'..'</span>){ <span>if</span>(strtolower(substr(<span>$file</span>, -<span>4</span>))==<span>'.php'</span>){ array_push(<span>$result</span>, <span>$file</span>); } } } } <span>return</span><span>$result</span>; } <span>?></span></span></span></code>
如使用glob方法来遍历则可以简化代码
<code><span><span><?php </span><span>$path</span> = dirname(<span>__FILE__</span>); <span>$result</span> = glob(<span>$path</span>.<span>'/*.php'</span>); print_r(<span>$result</span>); <span>?></span></span></span></code>
注意,glob返回的会是path+搜寻结果的路径,例如path=’/home/fdipzone’,以上例子则返回
<code><span>Array</span> ( [<span>0</span>] => <span>/home/</span>fdipzone/a.php [<span>1</span>] => <span>/home/</span>fdipzone/b.php [<span>2</span>] => <span>/home/</span>fdipzone/c.php )</code>
这是与opendir,readdir返回的结果不同的地方。
如果只是遍历当前目录。可以改成这样:glob(‘*.php’);
glob语法说明:
<code>array <span>glob</span> ( string <span>$pattern</span> [, <span>int</span><span>$flags</span> = <span>0</span> ] )</code>
glob() 函数依照 libc glob() 函数使用的规则寻找所有与 pattern 匹配的文件路径,类似于一般 shells 所用的规则一样。不进行缩写扩展或参数替代。glob使用正则匹配路径功能强大。
flags 有效标记有:
GLOB_MARK - 在每个返回的项目中加一个斜线
GLOB_NOSORT - 按照文件在目录中出现的原始顺序返回(不排序)
GLOB_NOCHECK - 如果没有文件匹配则返回用于搜索的模式
GLOB_NOESCAPE - 反斜线不转义元字符
GLOB_BRACE - 扩充 {a,b,c} 来匹配 ‘a’,’b’ 或 ‘c’
GLOB_ONLYDIR - 仅返回与模式匹配的目录项
GLOB_ERR - 停止并读取错误信息(比如说不可读的目录),默认的情况下忽略所有错误
例子:使用glob方法遍历指定文件夹(包括子文件夹)下所有php文件
<code><span><span><?php </span><span>$path</span> = dirname(<span>__FILE__</span>); <span>$result</span> = <span>array</span>(); traversing(<span>$path</span>, <span>$result</span>); print_r(<span>$result</span>); <span><span>function</span><span>traversing</span><span>(<span>$path</span>, &<span>$result</span>)</span>{</span><span>$curr</span> = glob(<span>$path</span>.<span>'/*'</span>); <span>if</span>(<span>$curr</span>){ <span>foreach</span>(<span>$curr</span><span>as</span><span>$f</span>){ <span>if</span>(is_dir(<span>$f</span>)){ array_push(<span>$result</span>, <span>$f</span>); traversing(<span>$f</span>, <span>$result</span>); }<span>elseif</span>(strtolower(substr(<span>$f</span>, -<span>4</span>))==<span>'.php'</span>){ array_push(<span>$result</span>, <span>$f</span>); } } } } <span>?></span></span></span></code>
版权声明:本文为博主原创文章,未经博主允许不得转载。
以上就介绍了使用glob方法遍历文件夹下所有文件,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。