PHP - 在zip存档中编辑文件,并在关闭之前另存为另一个存档名称

时间:2016-12-06 05:07:47

标签: php

我有一个Microsoft Word文件,我将其用作模板。 (testingsample.docx)计划是使用表单输入值来创建租赁协议。我在下面找到的代码非常适合打开.docx文件并查找和替换所需的字符串。问题是它只能工作一次。第一次运行时,它会覆盖我的模板。我试图找到一种方法来打开testingsample.docx,进行必要的字符串更改,并将存档保存为testingsamplecopy.docx而不更改testingsample.docx。

提前感谢您的帮助!

// Create the Object.
$zip = new ZipArchive();

$inputFilename = 'testingsample.docx';

// Open the Microsoft Word .docx file as if it were a zip file... because it is.
if ($zip->open($inputFilename, ZipArchive::CREATE)!==TRUE) {
    echo "Cannot open $inputFilename :( "; die;
}

// Fetch the document.xml file from the word subdirectory in the archive.
$xml = $zip->getFromName('word/document.xml');

// Replace the strings
$xml = str_replace("1111","Tenant Name Here",$xml);
$xml = str_replace("2222","Address Here",$xml);

// Write back to the document and close the object
if ($zip->addFromString('word/document.xml', $xml)) { echo 'File written!'; }
else { echo 'File not written.  Go back and add write permissions to this folder!l'; }

$zip->close();

header("Location: testingsample.docx");

?>

1 个答案:

答案 0 :(得分:1)

从模板文件到目标文件只需copy,然后打开目标文件而不是模板。

此外,我更改了header行的代码以使用文件名的变量而不是静态变量。

<?php

// Create the Object.
$zip = new ZipArchive();

$templateFilename = 'testingsample.docx';
$inputFilename = 'testingsamplecopy.docx';

if(!copy($templateFilename, $inputFilename)) {
    die("Could not copy '$templateFilename' to '$inputFilename');
}

// Open the Microsoft Word .docx file as if it were a zip file... because it is.
if ($zip->open($inputFilename, ZipArchive::CREATE)!==TRUE) {
    echo "Cannot open $inputFilename :( "; die;
}

// Fetch the document.xml file from the word subdirectory in the archive.
$xml = $zip->getFromName('word/document.xml');

// Replace the strings
$xml = str_replace("1111","Tenant Name Here",$xml);
$xml = str_replace("2222","Address Here",$xml);

// Write back to the document and close the object
if ($zip->addFromString('word/document.xml', $xml)) { echo 'File written!'; }
else { echo 'File not written.  Go back and add write permissions to this folder!l'; }

$zip->close();

// I also chaned this to use your variable instead of a static value.
header("Location: $inputFilename");

?>