php快速读取显示表格文件后缀,php 快速读取文件夹下文件列表

因为学习某个项目,需要文件函数,为了防止生疏,特意记载下来。

1:读取指定目录下的所有文件,或者匹配指定后缀的文件列表

//scadir函数负责扫描指定文件夹下的内容

$list = scandir('./');

//获取目录下所有php结尾的文件列表

$list = glob('*.php');

2:使用循环方式获取,注:$f就是一个文件目录,这里只是采用tp框架获取目录的写法

$f = Env::get('APP_PATH');

$resource = opendir($f.'index\lang');

while ($rows = readdir($resource)){

if($rows == "." || $rows == "..") {continue;}

var_dump($rows);

}

3:递归获取所有文件名

public function getFiles($path,&$finename)

{

//这里也可以使用dir方法

//$resource = dir($path);

//while里条件写成$rows = $resource->read();

$resource = opendir($path);

while ($rows = readdir($resource)){

if( is_dir($path.'/'.$rows) && $rows != "." && $rows != "..")

{

$this->getFiles($path.'/'.$rows,$finename);

}elseif($rows != "." && $rows != "..")

{

$finename[] = $rows;

}

}

}

public function index()

{

$f = Env::get('APP_PATH');

$path = $f.'index';

$finename = [];

$lists = $this->getFiles($path,$finename);

var_dump($finename);

die;

return $this->fetch();

}

附带一个完整的函数,方便使用各种查询

/*

* 获取指定目录下指定文件后缀的函数

* @$path 文件路径

* @$ext 文件后缀名,默认为false为不指定,如果指定,请以数组方式传入

* @$filename 使用时请提前赋值为空数组

* @$recursive 是否递归查找,默认为false

* @$baseurl 是否包含路径,默认包含

*/

function getDirFilesLists($path,&$filename,$recursive = false,$ext = false,$baseurl = true){

if(!$path){

die('请传入目录路径');

}

$resource = opendir($path);

if(!$resource){

die('你传入的目录不正确');

}

//遍历目录

while ($rows = readdir($resource)){

//如果指定为递归查询

if($recursive) {

if (is_dir($path . '/' . $rows) && $rows != "." && $rows != "..") {

getDirFilesLists($path . '/' . $rows, $filename,$resource,$ext,$baseurl);

} elseif ($rows != "." && $rows != "..") {

//如果指定后缀名

if($ext) {

//必须为数组

if (!is_array($ext)) {

die('后缀名请以数组方式传入');

}

//转换小写

foreach($ext as &$v){

$v = strtolower($v);

}

//匹配后缀

$file_ext = strtolower(pathinfo($rows)['extension']);

if(in_array($file_ext,$ext)){

//是否包含路径

if($baseurl) {

$filename[] = $path . '/' . $rows;

}else{

$filename[] = $rows;

}

}

}else{

if($baseurl) {

$filename[] = $path . '/' . $rows;

}else{

$filename[] = $rows;

}

}

}

}else{

//非递归查询

if (is_file($path . '/' . $rows) && $rows != "." && $rows != "..") {

if($baseurl) {

$filename[] = $path . '/' . $rows;

}else{

$filename[] = $rows;

}

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值