用PHP来搜索和替换POST变量DOCX文档中

问题描述 投票:0回答:2

我试图做一个搜索,并在一个Microsoft Word文档DOCX更换。我遇到的奇怪的问题是,在7个发布瓦尔的,1和5并没有取代。在检查Google Chrome工具,它们都出现在提交的表单数据。的名字都被拼写正确了。

为了解释这个代码,我打开一个模板文档,将其复制到另一个名称(命名的文件,该文件就会被下载),在document.xml中替换文本,然后在页脚替换文本。然后我关闭该文件并下载。它的下载,除了时,VARS $ 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();
}
?>
php str-replace docx
2个回答
0
投票

对于任何未来的读者遇到类似的问题的好处,当我分析了压缩的docx文件中的document.xml中的文件,我的变量名往往是不连续的,而不是{} PNAME将它分隔成{PNAME

打开你主文档模板,得到了文件,检查文档,检查是否有问题。这将允许你清理的文件,并删除多,中间的XML对此,我认为,是一些文件跟踪数据。

它为我工作。


0
投票

是检查你的document.xml中和footer1.xml file.Your领域应该是连续的,但我有你的代码一个问题,当文件下载它不是在Word中打开显示一些错误。

© www.soinside.com 2019 - 2024. All rights reserved.