遍歷資料夾下所有文件,一般可以使用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></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></code>
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>
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()glob() 函式依照libc glob()glob()
函式依照libc glob()
glob() 函式依照libc glob()
函式使用的規則尋找所有符合的檔案路徑,類似一般shells 所使用的規則一樣。不進行縮寫擴充或參數替代。 glob使用正規匹配路徑功能強大。 flags 有效標記有:
GLOB_MARK - 在每個傳回的項目中加上一個斜線
GLOB_NOSORT - 在目錄中出現的原始檔案加一個斜線
GLOB_NOSORT - 依照檔案在目錄中出現的原始檔案在目錄中返回(不排序)
-匹配則傳回用於搜尋的模式GLOB_NOESCAPE
- 僅傳回與模式相符的目錄項目
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></code>