【问题标题】:How to convert a file to zip in php如何在php中将文件转换为zip
【发布时间】:2020-03-20 11:34:38
【问题描述】:

我必须将 php 中呈现的文件转换为 zip 文件。

这是我的代码:

 $cacheContent = $gRender->getRenderRaw(
                    "feed-google", array(
                    "_context_" => $this->getType(),
                    "_lang_" => $this->getLang()->getId(),
                    "_id_" => $id));


                $cacheDriver->save($cacheKey, $cacheContent, $cacheExpire);

你能帮我如何将 cacheContent 转换为 zip 吗?

编辑: 在缓存文件夹中生成一个哈希文件,格式如下:5d.doctrinecache.data

每次生成文件名更改。里面的这个文件是这样的:

    <?xml version="1.0"?>
    <rss version="2.0"  xmlns:g="http://google.com">
                <channel>
                                <title>Item</title>
                    <link></link>
                    <description></description>
                    <language></language>
                    <lastBuildDate></lastBuildDate>
                    <generator></generator>

                <item>
  </item>    
        </channel>
    </rss>

这个文件我要转换成 zip 格式

【问题讨论】:

标签: php symfony zipfile


【解决方案1】:

试试这个:

$rootPath = $_SERVER['DOCUMENT_ROOT'];
$backup_name = "exported_zip_file.zip";
$file_name   = "cacheContent.xml";
$file_content = "cacheContent"; // your string
$zip = new ZipArchive();
$zip -> open($rootPath . "/" . $backup_name, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip -> addFromString($file_name, $file_content);
$zip -> close();

/* this can be deleted */

$zip_final = $rootPath . "/" .$backup_name;
//
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename = ".$backup_name);
header("Content-Length: " . filesize($zip_final));
//
if(readfile($zip_final)) {
    exit;
}

基本上,您是在 $backup_name 中定义 zip 的名称。

接下来,您将在 $file_name 中定义文件的名称。

接下来,您将在 $file_content 中定义文件中的内容。

接下来您将创建或覆盖一个新的 zip 存档。

接下来您将创建一个新文件并将您的 $file_content 添加到其中。

最后关闭 zip 文件。

“这可以删除”上方是一些标题,可让您的浏览器下载新的 .zip 文件

【讨论】:

  • 警告:dirname() 期望参数 2 为整数,字符串给定我有这个警告
  • 问题出在:$zip -> addFile(dirname($rootPath . "/" . $backup_name, $backup_name));我唯一的改变是 rootPath ,我做了: $rootPath = THELIA_CACHE_DIR 。 DS 。自我::FEED_CACHE_DIR;
  • 对不起,我是 php 新手,我不知道,但我还有其他问题:警告:ZipArchive::addFile(): Invalid or uninitialized Zip object
  • my_string.txt 创建但未创建 zip
猜你喜欢
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
  • 2018-07-13
  • 2011-04-22
  • 2016-12-30
  • 2012-06-16
  • 2012-01-12
相关资源
最近更新 更多