php中文网 | cnphp.com

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 728|回复: 0

php遍历文件夹及其子文件夹的指定类型文件,读取文件内...

[复制链接]

2871

主题

2881

帖子

1万

积分

管理员

Rank: 9Rank: 9Rank: 9

UID
1
威望
0
积分
7283
贡献
0
注册时间
2021-4-14
最后登录
2024-9-19
在线时间
715 小时
QQ
发表于 2022-1-15 20:20:11 | 显示全部楼层 |阅读模式
[mw_shl_code=applescript,true]<?php
$fileList = array();
$dir = $_SERVER['DOCUMENT_ROOT']."/用户异常申请报告单文件夹2";//服务器根目录下某个文件夹
$ext =".php";//包含某个特定字符串的文件,这里使用文件后缀
$word="123";//读取文件中内容,匹配相应字符串

findWord($dir,$ext,$word);

/*
   功能:遍历文件夹及其子文件夹的指定类型文件,读取文件内容并找到含某关键字文件
   输入:$dir 目录 , $ext 文件后缀, $word 关键字
   输出:文件List
*/
function findWord($dir,$ext,$word){
  $rList = array();
  $list = read_all_dir ( $dir,$ext );
  foreach($list as $file){
      $c = file_get_contents($file);
      if(strpos($c,$word)!==false){
        $rList[]=$file;
      }
  }
  print_r($rList);
}
/*
     遍历某个目录下的所有文件和子文件夹,返回某个后缀的文件列表;
*/
function read_all_dir ($dir){
  global $fileList,$ext;
  $result = array();
  $handle = opendir($dir);
  if ($handle){
    while ( ( $file = readdir ( $handle ) ) !== false ){
      if($file != '.' && $file != '..'){
        $cur_path = $dir . DIRECTORY_SEPARATOR . $file;
        if ( is_dir ( $cur_path ) ){
          $result['dir'][$cur_path] = read_all_dir ( $cur_path );
        }else{
          $result['file'][] = $cur_path;
          if(strpos($cur_path,$ext)!==false){
            $fileList[]= $cur_path;
          }
        }
      }
    }
    closedir($handle);
  }
  return $fileList;
}[/mw_shl_code]

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|php中文网 | cnphp.com ( 赣ICP备2021002321号-2 )

GMT+8, 2024-9-20 05:50 , Processed in 0.178479 second(s), 30 queries , Gzip On.

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2020, Tencent Cloud.

申明:本站所有资源皆搜集自网络,相关版权归版权持有人所有,如有侵权,请电邮(fiorkn@foxmail.com)告之,本站会尽快删除。

快速回复 返回顶部 返回列表