使用PHP搜索和替换docx文档中的POST变量



我正在尝试做一个搜索和替换微软Word docx文档。我遇到的奇怪问题是,在7个发布的变量中,1和5不替换。在检查Chrome工具,他们都出现在张贴表单数据。名字也都拼对了。

为了解释这段代码,我打开一个模板文档,将其复制到另一个名称(将下载的命名文件),替换document.xml中的文本,然后替换页脚中的文本。然后我关闭文件并下载它。它可以下载,只是变量$pname和$hca2name不能在文档内部替换。所有其他变量都被正确替换。

任何想法都非常感谢。谢谢你!下面是代码:

<?php
$pname = (string) $_POST['pname'];
$countyres = (string) $_POST['countyres'];
$a1name = (string) $_POST['a1name'];
$a2name = (string) $_POST['a2name'];
$hca1name = (string) $_POST['hca1name'];
$hca2name = (string) $_POST['hca2name'];
$atty = (string) $_POST['atty'];
$countyres = (string) $_POST['countyres'];
$fn = 'POA-'.$pname.'.docx';
$s = "docs_archive/PA-poas2no.docx";
$wordDoc = "POA-".$pname.".docx";
copy($s, $wordDoc);
$zip = new ZipArchive;
//This is the main document in a .docx file.
$fileToModify = 'word/document.xml';
if ($zip->open($wordDoc) === TRUE) {
    //Read contents into memory
    $oldContents = $zip->getFromName($fileToModify);
    //Modify contents:
    $newContents = str_replace('{pname}', $pname, $oldContents);
    $newContents = str_replace('{a1name}', $a1name, $newContents);
    $newContents = str_replace('{a2name}', $a2name, $newContents);
    $newContents = str_replace('{hca1name}', $hca1name, $newContents);
    $newContents = str_replace('{hca2name}', $hca2name, $newContents);
    $newContents = str_replace('{atty}', $atty, $newContents);
    $newContents = str_replace('{countyres}', $countyres, $newContents);
    //Delete the old...
    $zip->deleteName($fileToModify);
    //Write the new...
    $zip->addFromString($fileToModify, $newContents);
    //Open Footer and change vars there
    $ft = 'word/footer1.xml';
    $oldft = $zip->getFromName($ft);
    $newft = str_replace('{pname}', $pname, $oldft);
    $zip->deleteName($ft);
    $zip->addFromString($ft, $newft);
    $zip->close();
header('Content-Description: File Transfer');
header("Content-Type: application/force-download");
header('Content-Type: application/msword');
header('Content-Disposition: attachment; filename="'.$fn.'"');
header('Content-Transfer-Encoding: binary');
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
readfile($fn);
unlink($fn);
exit();
}
?>

为了方便将来遇到类似问题的读者,当我分析压缩docx文件中的document.xml文件时,我的变量名通常不是连续的,而不是{pname}它将被分隔成{pname

打开你的主文件模板,进入文件,检查文件,检查问题。这将允许您清理文件并删除大部分中间xml,我认为这些xml是一些文档跟踪数据。

是的,检查您的document.xml和footer1.xml文件。你的字段应该是连续的,但我有一个问题,你的代码当文件下载时,它不是打开word显示一些错误。

最新更新