PHP遍历目录下的文件夹和文件 以及遍历文件下内容

时间:2022-01-08 12:27:18

1.遍历目录下的文件夹和文件:

 1 public function bianli1($dir)
 2     {
 3         $files = array();
 4         if($head = opendir($dir))
 5         {
 6             while(($file = readdir($head)) !== false)
 7             {
 8                 if($file != ".." && $file!=".")
 9                 {
10                    if(is_dir($file))
11                    {
12                        $files[$file]=bianli1($dir.'/'.$file);
13                    }
14                    else
15                    {
16                        $files[]=$file;
17                    }
18                 }
19             }
20         }
21         closedir($head);
22         return $files;
23     }

2.遍历文件下内容:

 1 function bianli2()
 2     {
 3         $hostdir= iconv("utf-8","gbk","D:/wamp/www") ;
 4         $filesnames = scandir($hostdir);
 5         foreach ($filesnames as $name) {
 6             if($name!=".." && $name!=".")
 7             {
 8                 $cipath = $hostdir.$name;
 9                 $cjfilenames = scandir($cipath);
10                 foreach($cjfilenames as $cjname)
11                 {
12                     if($cjname!=".." && $cjname!="." &&!is_dir($cipath."/".$cjname))
13                     {
14                         $str = file_get_contents($cipath."/".$cjname);
15                         file_put_contents("D:/test.txt",$str,FILE_APPEND);
16                     }
17                 }
18             }
19             echo "\n";
20         }
21     }