0

我正在使用以下功能创建一个 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

怎么做?

4

1 回答 1

0

您需要使用createModify 方法- 它比 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'
);
?>
于 2014-01-24T16:01:07.287 回答