从多个方向读取文件

时间:2013-11-18 14:52:18

标签: php sql

我正在尝试创建一个脚本,从某个文件夹中的多个目录中读取.sql文件,然后将它们执行到数据库中。

如何让我的代码能够读取多个文件夹。 [将来会添加/删除这些文件夹,所以我需要它来自动查找任何没有任何部分名称的文件夹。

所以例如我有一个名为“mysqls”的文件夹,在该文件夹中我有其他文件夹,例如'text1','test2'。 Test1和test2有不同的.sql文件,我希望这样做。

<?php
$dirf    = 'mysqls';
$dir = scandir($dirf);

unset($dir['0']);
unset($dir['1']);

foreach($dir as $file) {


       $sql = file_get_contents($dirf . '/'. $file);
       $qr = $dbh->exec($sql);
}

?> 

3 个答案:

答案 0 :(得分:0)

$directory = new RecursiveDirectoryIterator('mysqls');

// Filter out "dot" folders
$filter = new DirnameFilter($directory, '/^(?!\.)/');

// Filter sql files 
$filter = new FilenameFilter($filter, '/(?:sql)$/i');

foreach(new RecursiveIteratorIterator($filter) as $file) {
    $sql = file_get_contents($file);
    $qr = $dbh->exec($sql);
}


abstract class FilesystemRegexFilter extends RecursiveRegexIterator {
    protected $regex;
    public function __construct(RecursiveIterator $it, $regex) {
        $this->regex = $regex;
        parent::__construct($it, $regex);
    }
}

class FilenameFilter extends FilesystemRegexFilter {
    // Filter files against the regex
    public function accept() {
        return ( ! $this->isFile() || preg_match($this->regex, $this->getFilename()));
    }
}

class DirnameFilter extends FilesystemRegexFilter {
    // Filter directories against the regex
    public function accept() {
        return ( ! $this->isDir() || preg_match($this->regex, $this->getFilename()));
    }
}

答案 1 :(得分:0)

使用RecursiveIteratorIterator()

也许是这样的
<?php 
function scan_for_sql_files($path){
    $itdir = new \RecursiveIteratorIterator(
    new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS),
    \RecursiveIteratorIterator::SELF_FIRST,
    \RecursiveIteratorIterator::CATCH_GET_CHILD);
    $files = array();
    foreach ($itdir as $path=>$dir){
        if ($dir->isFile()){
            $ext = substr(strtolower($path), -3);
            if($ext == 'sql'){
                $files[] = array('path' => $path);
            }
        }
    }
    return $files;
}

//get files
$files = scan_for_sql_files('mysqls');
//Do sql
foreach($files as $file){
    $sql = file_get_contents($file['path']);
    $qr = $dbh->exec($sql);
}
?>

答案 2 :(得分:0)

$iterator = new RecursiveDirectoryIterator('mysqls');
foreach($iterator as $fileinfo){
    if('sql' == $fileinfo->getExtension()){
        $sql = file_get_contents($fileinfo->getPathname());
        $qr = $dbh->exec($sql);
    }
}