【问题标题】:How do you zip 3 small text files and force download with Zend Framework如何使用 Zend Framework 压缩 3 个小文本文件并强制下载
【发布时间】:2010-02-05 00:08:51
【问题描述】:

是否有 Zend Framework 方法来保存 3 个文件中的内容(无论是动态生成的还是实际存在的)并强制下载为文件?

类似于这个问题(尽管尝试了几种不同的方法,但到目前为止从控制器内部运行时它对我不起作用):

PHP Zip 3 small text files and force download

【问题讨论】:

    标签: zend-framework zip


    【解决方案1】:

    您可以像这样使用 PHP ZIP 库(您需要预先安装该库):

    $zip = new ZipArchive();
    if($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true){
        throw new Exception('Could not create zip file ' . $filename);
        die('zip fail');
    }else{
        $zip->addFile($file1Uri, 'file1.txt');
        $zip->addFile($file2Uri, 'file2.txt');
    }
    
    $zip->close();
    
    if(file_exists($filename)){
        return true;            
    }else{
        throw new Exception('Could not create zip file ' . $filename);
    }
    

    提供 ZIP 文件:

    protected function _deliver($file, $name, $extension, $size, $mime){
        header('Pragma: private');
        header("Expires: -1");
        header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT'); 
        header("Cache-Control: no-cache");
        header("Content-Transfer-Encoding: binary");
        header("Content-Type: " . $mime);
        header("Content-Description: File Transfer"); 
        header('Content-Disposition: attachment; filename="' . $name . '.' . $extension . '"');
        header("Content-Length: " . $size);
        set_time_limit(0);        
        if(!readfile($file)){
            return false;
        }
    }
    

    【讨论】:

      【解决方案2】:

      答案是对您的另一个问题的赞成票。从控制器执行此操作,然后在输出 zip 数据后调用 exit,因此不要渲染视图。

      【讨论】:

      • 我在 addFile 或 addFromString 上收到此错误(我都尝试过):“无效或未初始化的 Zip 对象”即使我执行 file_get_contents 并将其回显,数据也是有效的。
      • 你必须调用 $zip->open($filename)。具有唯一的文件名(可能是用户的会话 ID)。您无法在内存中创建 zip。
      • 啊,有道理。所以基本上赞成的答案是错误的?它没有 $zip->open($file) & 在 cmets 中说“它只是在回显它之前将它保存在内存中。”
      • 是的,这很令人沮丧,但我之前遇到过同样的问题。它可能取决于php版本。
      • 也许还有 windows vs *nix。我希望它在两个环境中都能工作。现在去测试一下。
      猜你喜欢
      • 2010-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      • 2015-02-10
      相关资源
      最近更新 更多