PHP-在zip存档中编辑文件,并在关闭前另存为另一个存档名称
我有一个Microsoft Word文件用作模板。(testingsample.docx)计划使用表单输入值创建租赁协议。我在下面找到的代码可以很好地打开.docx文件并查找和替换所需的字符串。问题是它只工作一次。第一次运行时,它会覆盖我的模板。我正在试图找到一种方法来打开testingsample.docx,进行所需的字符串更改,并在不更改testingsamplecopy.docx的情况下将存档保存为testingsamplecopy.docx 提前感谢您的帮助PHP-在zip存档中编辑文件,并在关闭前另存为另一个存档名称,php,Php,我有一个Microsoft Word文件用作模板。(testingsample.docx)计划使用表单输入值创建租赁协议。我在下面找到的代码可以很好地打开.docx文件并查找和替换所需的字符串。问题是它只工作一次。第一次运行时,它会覆盖我的模板。我正在试图找到一种方法来打开testingsample.docx,进行所需的字符串更改,并在不更改testingsamplecopy.docx的情况下将存档保存为testingsamplecopy.docx 提前感谢您的帮助 // Create the
// 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");
?>
只需将从模板文件复制到目标文件,然后打开目标文件而不是模板 此外,我还更改了
标题
行中的代码,以使用文件名变量,而不是静态变量
<?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");
?>