1

所以这是我的代码:

<?php

$zip = new ZipArchive;
if ($zip->open('test.docx') === TRUE) {

 $xmlString = $zip->getFromName('word/document.xml');
 $xmlString = str_replace('$FIRST_AND_LAST_NAME', 'John Doe', $xmlString);
    $zip->addFromString('word/document.xml', $xmlString);

 echo 'ok';

    $zip->close();
} else {
    echo 'failed';
}

它的目的很简单。它打开一个 test.docx 文件,搜索所有出现的字符串“$FIRST_AND_LAST_NAME”,并将它们替换为“John Doe”。

它在我的 Windows 开发服务器上完美运行(当我打开它时,“John Doe”字符串在文档中)。

它在我的 Lunux 生产服务器上不起作用(“$FIRST_AND_LAST_NAME”字符串仍然存在,没有“John Doe”)。

没有错误或通知,“ok”打印没有任何错误。我确保 test.docx 文件的权限设置为 777。

4

3 回答 3

1

如果close()返回 false,则写出存档时出错。

用于getStatusString获取确切的错误消息。

于 2010-08-25T14:16:54.603 回答
1

sleep(1)之前添加$zip->addFromString('word/document.xml', $xmlString);

它适用于我的 Ubuntu 12.04

不要忘记在创建 docx 文件的同时键入变量,我的意思是永远不要键入FIRST_AND_LAST_NAME,然后在$之后添加一个符号。它创建不同的 XML 代码。

于 2012-10-18T04:52:19.917 回答
0

好的,我使用了我在 phpclasses 找到的一个类:

http://phpclasses.web4u.cz/package/6278-PHP-Edit-a-Zip-archive-in-pure-PHP-no-temporary-files.html

这是工作代码:

private function GenerateDocx($theTemplate, array $theReplacemenArray, $theOutputFile)
{
    $aSearchArray = array();
    foreach(range('A','Z') as $aLetter) {
        $aSearchArray[] = str_repeat($aLetter, 5);
    }
    $aArrayCountDifference = count($aSearchArray) - count($theReplacemenArray);
    $aSearchArray = array_slice($aSearchArray, 0, -$aArrayCountDifference);     

    require_once('tbszip.php');
    $tbszip = new clsTbsZip();
    $tbszip->Open($theTemplate);

    $aXmlPath = 'word/document.xml';

    if (true === $tbszip->FileExists($aXmlPath)) {

        $aXmlString = $tbszip->FileRead($aXmlPath);

        $aXmlString = str_replace($aSearchArray, $theReplacemenArray, $aXmlString);

        if (1 != $tbszip->FileReplace($aXmlPath, $aXmlString)) {
            throw new Exception('FileReplace() failed.');
        }

        $tbszip->Flush(TBSZIP_FILE, $theOutputFile);

        $tbszip->Close();

    }
}
于 2010-08-26T08:16:01.480 回答