php教程目录,目录操作_PHP

这段代码展示了一个PHP类`DirTree`,用于遍历指定目录及其子目录,过滤特定类型的文件,并执行指定操作。在示例中,创建了两个接口`DirAction`和`DirFilter`,`Gbk2Utf8Action`实现了将GBK编码的HTML和PHP文件转换为UTF-8编码,而`HtmlPhpFilter`则作为过滤器只处理HTML和PHP文件。整个过程用于批量处理目录中的文件编码转换。
摘要由CSDN通过智能技术生成

* @Created

* @Version $Id$

*/

define('_DEBUG', 1);

class DirTree

{

private $_dirRoot;

private $_filter;

private $_tmpBuff = array();

public function __construct($dirRoot = '.')

{

$this->_dirRoot = $dirRoot;

}

//使用 过滤器 或者 设置 $_safeFile ....

public function setFilter($filter)

{

$this->_filter = $filter;

}

public function listDirFile($dir = '', $action='')

{

$curDir = ( empty($dir) ) ? $this->_dirRoot : $dir;

$dh = @opendir($curDir);

while ( $tmpName = readdir($dh) )

{

if ( ($tmpName == '.') || ($tmpName == '..') ) continue;

$totalPath = $curDir . '/' . $tmpName;

if ( is_object($this->_filter) )

{

if ( $this->_filter->doFilter($totalPath) ) continue;

}

if ( is_dir($totalPath) )

{

$this->_tmpBuff['0'][] = $tmpName;

if ( _DEBUG )

{

echo 'is dir:' . $totalPath . '

';

}

if ( is_object($action) )

{

$action->doAction($totalPath);

}

$this->listDirFile($totalPath, $action);

}

else

{

$this->_tmpBuff['1'][] = $tmpName;

if ( _DEBUG )

{

echo 'is file:' . $totalPath . '

';

}

if ( is_object($action) )

{

$action->doAction($totalPath);

}

}

}

closedir($dh);

}

}

interface DirAction

{

public function doAction($args);

}

interface DirFilter

{

public function doFilter($args);

}

class NowAction implements DirAction

{

public function doAction($args)

{

if ( _DEBUG )

{

$numArgs = func_num_args();

echo $numArgs . '

';

for( $i = 0; $i < $numArgs; $i++ )

print_r(func_get_arg($i) . '

');

}

}

}

=====================================================

应用 部分

set_time_limit(0);

require 'DirTree.php';

class Gbk2Utf8Action implements DirAction

{

public function doAction($args)

{

$aimPath = ereg_replace('D:/html/web','D:/back', $args);

if ( is_file($args) )

{

$file = implode ('', file($args));

$content = iconv("gb2312", "UTF-8", $file);

$fh = fopen($aimPath, 'w');

fwrite($fh, $content);

fclose($fh);

}

else

{

mkdir($aimPath);

}

}

}

class HtmlPhpFilter implements DirFilter

{

public function doFilter($args)

{

$suffix = substr(strrchr($args, '.'), 1);

if ( ('htm' == $suffix) || ('php' == $suffix) )

return false;

else if ( is_dir($args) )

return false;

else

return true;

}

}

$dirTree = new DirTree();

$action = new Gbk2Utf8Action();

$filter = new HtmlPhpFilter();

$dirTree->setFilter($filter);

$dirTree->listDirFile('D:/html/web', $action);

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值