使用pear Archive_Tar创建存档

时间:2013-08-28 11:18:51

标签: php tar

我正在使用以下功能创建tar存档

public static function packDirectory($path, $outpath) {
    require_once 'Archive/Tar.php';

    $obj = new Archive_Tar($outpath);
    $obj->setErrorHandling(PEAR_ERROR_PRINT);

    $handle=opendir($path);
    $files = array();

    while (false !== ($file = readdir($handle))) {
        if ($file == '.' || $file == '..') {
            continue;
        }

        $files[] = $path . '/' . $file;
    }

    $obj->create($files);
}

路径类似于folder1/folder2/folder3/。它创建了一个类似于以下

的存档
folder1/folder2/folder3/fileA
folder1/folder2/folder3/fileB
folder1/folder2/folder3/fileC
folder1/folder2/folder3/subfolder/fileD

我希望那是

fileA
fileB
fileC
subfolder/fileD

如何做到?

1 个答案:

答案 0 :(得分:0)

您需要使用createModify method - 它比Archive_Tar的create方法多两个参数。要完成,这三个参数是:

  • $ p_filelist - 文件名数组
  • $ p_add_dir - 要添加到文件名前的字符串/路径。
  • $ p_remove_dir - 要从文件名中删除的字符串/路径。

我稍微更改了packDirectory方法,以包含要从文件名中删除的内容的第三个参数。它看起来像这样:

<?php
class Packer {

    public static function packDirectory($path, $outpath, $stripPath = '') {
        require_once 'Archive/Tar.php';

        $obj = new Archive_Tar($outpath);
        $obj->setErrorHandling(PEAR_ERROR_PRINT);

        $handle=opendir($path);
        $files = array();

        while (false !== ($file = readdir($handle))) {
            if ($file == '.' || $file == '..') {
                continue;
            }

            $files[] = $path . '/' . $file;
        }

        if ($stripPath === '') {
            $obj->create($files);
        } else {
            $obj->createModify($files, '', $stripPath);
        }
    }
}

Packer::packDirectory(
    "folder1/folder2/folder3", 
    "Packer.tar", 
    'folder1/folder2/folder3'
);
?>