在 PHP 中修改 ZIP 文件中的单个文本文件 [英] Modifying a single text file in a ZIP file, in PHP
问题描述
我的服务器上有一个 ZIP 文件.我想创建一个接受单个参数的 PHP 文件 loadZIP.php,然后修改 ZIP 中的一个文本文件以反映该参数.
I have a ZIP file on my server. I want to create a PHP file, loadZIP.php that will accept a single parameter, and then modify a text file within the ZIP to reflect that parameter.
因此,访问 loadZIP.php?param=blue
,将打开 zip 文件,并将我指定的文本文件中的一些文本替换为blue",并允许用户下载此文件已编辑的 zip 文件.
So, accessing loadZIP.php?param=blue
, will open up the zip file, and replace some text in a text file I specify with 'blue', and allow the user to download this edited zip file.
我查看了所有 PHP ZIP 函数,但找不到简单的解决方案.这似乎是一个相对容易的问题,我相信我想多了.在我开始编写一些过于复杂的函数之前,我想知道你会怎么做.
I've looked over all of the PHP ZIP functions, but I can't find a simple solution. It seems like a relatively easy problem, and I believe I'm over thinking it. Before I go and write some overly complex functions, I was wondering how you'd go about this.
推荐答案
你看过 PHP5 的 ZipArchive
函数吗?
Have you taken a look at PHP5's ZipArchive
functions?
基本上,您可以使用 ZipArchive::Open()
打开 zip,然后 ZipArchive::getFromName()
将文件读入内存.然后,修改它,使用 ZipArchive::deleteName()代码>
删除旧文件,使用 ZipArchive::AddFromString()
将新内容写回 zip,并且 ZipArchive::close()
:
Basically, you can use ZipArchive::Open()
to open the zip, then ZipArchive::getFromName()
to read the file into memory. Then, modify it, use ZipArchive::deleteName()
to remove the old file, use ZipArchive::AddFromString()
to write the new contents back to the zip, and ZipArchive::close()
:
$zip = new ZipArchive;
$fileToModify = 'myfile.txt';
if ($zip->open('test1.zip') === TRUE) {
//Read contents into memory
$oldContents = $zip->getFromName($fileToModify);
//Modify contents:
$newContents = str_replace('key', $_GET['param'], $oldContents)
//Delete the old...
$zip->deleteName($fileToModify)
//Write the new...
$zip->addFromString($fileToModify, $newContents);
//And write back to the filesystem.
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
注意 ZipArchive 是在 PHP 5.2.0 中引入的(但是,ZipArchive 也可用作 PECL 包).
Note ZipArchive was introduced in PHP 5.2.0 (but, ZipArchive is also available as a PECL package).
这篇关于在 PHP 中修改 ZIP 文件中的单个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!