繁体   English   中英

使用 PHP 创建 Zip 文件?

[英]Creating a Zip file with PHP?

这是我第一次尝试在 PHP 中创建 ZIP 文件。

我正在做的是,我的 PHP 将在某个目录中搜索文件,将它们全部抓取并保存到 ZIP 文件中。 zip 文件随后会将文件发送到浏览器进行下载。 我非常接近,但我被困在某个部分。

这是我的代码:

    $zip = new ZipArchive();
    if ($zip->open('test.zip', ZIPARCHIVE::CREATE) !== TRUE) {
    die ("Could not open archive"); }

    $myDirectory = opendir("../folder/plugins/".$id."");

    while($entryName = readdir($myDirectory)) { $dirArray[] = $entryName; }
    closedir($myDirectory);
    $indexCount = count($dirArray);
    sort($dirArray);
    for($index=0; $index < $indexCount; $index++) {
    if (substr("$dirArray[$index]", 0, 1) != "."){

    $file = "".$myDirectory."".$dirArray[$index].".zip";

    $zip->addFile($file, $file) or die ("cant add file");  ; 
    echo $dirArray[$index]; echo '</br>';

    }}

    $zip->close()or die("cant close");

尝试关闭时出现“无法关闭”错误。 请在这里帮助我,我在我的代码中找不到我做错了什么。 这是它正在打印的内容:

   filename1.png
   filename2.png
   can't close

:)

检查以下行:

$zip->addFile($file, $file)

这是你真正想要达到的目标吗?

这是我如何让它工作的:

    <?php

        $dirArray = array();

        /* creates a compressed zip file */
        $zip = new ZipArchive;
        if ($zip->open('dataminefiles.zip', ZIPARCHIVE::CREATE) !== TRUE) {
            die ("Could not open archive"); 
        }
        // open the current dir
        if ($handle = opendir('.')) {
        while (false !== ($entry = readdir($handle))) {
            // ignore hidden files          
            if ($entry != "." && $entry != "..") {
            // only zip specific files
                if ( substr($entry,-3,3) == "jpg" || substr($entry,-3,3) == "pdf" || substr($entry,-3,3) == "lsx" || substr($entry,-3,3) == "xls" || substr($entry,-3,3) == "doc" || substr($entry,-3,3) == "txt" || substr($entry,-3,3) == "png" || substr($entry,-3,3) == "gif" || substr($entry,-3,3) == "peg" ) {
                    // if allowed, add them to the array
                    $dirArray[] = $entry;
                }
            }
        }
        closedir($handle);
    }

        $indexCount = count($dirArray);
        sort($dirArray);
            // loop through the files and add them to the zip file
        for($index=0; $index < $indexCount; $index++) {
                $file = "{$dirArray[$index]}";
                $zip->addFile($file, $file);
        }
    // close the zip file
        $zip->close();

    ?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM