Answers:
不知道使用7z
或zip
直接使用工具的方式。但是,猜想大多数库(例如perl,python等)都有一个zip
模块。您不能,但是可以在Bash中进行。
这是PHP中的一个简单示例:
$ mkdir -p A/B C/D E/F
$ touch A/B/f1.txt C/D/f2.txt E/F/f3.txt
$ tree .
.
├── A
│ └── B
│ └── f1.txt
├── C
│ └── D
│ └── f2.txt
├── E
│ └── F
│ └── f3.txt
$ ./php_zip -v out.zip -p x/y */*/f?.txt
$ 7z l out.zip
Listing archive: out.zip
Path = out.zip
Type = zip
Physical Size = 310
Date Time Attr Size Compressed Name
------------------- ----- ------------ ------------ ------------------------
2013-04-28 10:24:36 ..... 0 0 x/y/f1.txt
2013-04-28 10:24:36 ..... 0 0 x/y/f2.txt
2013-04-28 10:24:36 ..... 0 0 x/y/f3.txt
------------------- ----- ------------ ------------ ------------------------
0 0 3 files, 0 folders
./php_zip [-v|--verbose] archive.zip [<-p|--path> archive-path] files ...
--verbose Verbose; print what is added and where.
archive.zip Output file. Created if does not exist, else extended.
--path Target path in zip-archive where to add files.
If not given source path's are used.
files 0+ files.
If -P or --Path (Capital P) is used empty directory entries is added as well.
(很长一段时间没有编码PHP。无论如何,该代码仅是作为示例进行扩展或其他。)
#!/usr/bin/php
<?php
$debug = 0;
function usage($do_exit=1, $ecode=0) {
global $argv;
fwrite(STDERR,
"Usage: " . $argv[0] .
" [-v|--verbose] archive.zip" .
" [<-p|--path> archive-path]" .
" files ...\n"
);
if ($do_exit)
exit($ecode);
}
$zip_eno = array(
ZIPARCHIVE::ER_EXISTS => "EXISTS",
ZIPARCHIVE::ER_INCONS => "INCONS",
ZIPARCHIVE::ER_INVAL => "INVAL",
ZIPARCHIVE::ER_MEMORY => "MEMORY",
ZIPARCHIVE::ER_NOENT => "NOENT",
ZIPARCHIVE::ER_NOZIP => "NOZIP",
ZIPARCHIVE::ER_OPEN => "OPEN",
ZIPARCHIVE::ER_READ => "READ",
ZIPARCHIVE::ER_SEEK => "SEEK"
);
function zip_estr($eno) {
switch ($eno) {
case ZIPARCHIVE::ER_EXISTS:
}
}
if ($debug)
print_r($argv);
if ($argc > 1)
if ($argv[1] == "-h" || $argv[1] == "--help")
usage();
if ($argc < 3)
usage(1, 1);
$verbose = 0;
$path = "";
$add_dir = 0;
$zip = new ZipArchive();
$i = 1;
if ($argv[$i] == "-v" || $argv[$i] == "--verbose") {
if ($argc < 4)
usage(1, 1);
$verbose = 1;
++$i;
}
$zip_flag = file_exists($argv[$i]) ?
ZIPARCHIVE::CHECKCONS :
ZIPARCHIVE::CREATE;
if (($eno = $zip->open($argv[$i++], $zip_flag)) !== TRUE) {
fwrite(STDERR,
"ERR[$eno][$zip_eno[$eno]]: ".
"Unable to open archive " .
$argv[$i - 1] . "\n"
);
exit($eno);
}
if (
$argv[$i] == "-P" || $argv[$i] == "--Path" ||
$argv[$i] == "-p" || $argv[$i] == "--path"
) {
if ($argc - $i < 2)
usage(1, 1);
$path = $argv[$i + 1];
if (substr($path, -1) !== "/")
$path .= "/";
if ($argv[$i][1] == "P")
$zip->addEmptyDir($path);
$i += 2;
}
$eno = 0;
for (; $i < $argc; ++$i) {
if ($path !== "")
$target = $path . basename($argv[$i]);
else
$target = $argv[$i];
if ($verbose)
printf("Adding %s to %s\n", $argv[$i], $target);
if (!$zip->addFile($argv[$i], $target)) {
fwrite(STDERR, "Failed.\n");
$eno = 1;
}
}
$zip->close();
exit($eno);
?>