开发者

Problem saving edited zip archive (docx)

So here is my code:

<?php

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

 $xmlString = $zip-&开发者_如何学编程gt;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';
}

Its purpose is simple. It opens a test.docx file, searches for all occurences of a string "$FIRST_AND_LAST_NAME" and replaces them with "John Doe".

It works perfectly on my Windows development server (the "John Doe" string is in the docuemnt when I open it).

It does not work on my Lunux production server ("$FIRST_AND_LAST_NAME" string is still there, there is no "John Doe").

There is no error or notice, the "ok" is printed without any errors. I made sure the test.docx file has priviledges set to 777.


If close() returns false, there was an error writing out the archive.

Use getStatusString to get the exact error message.


Add sleep(1) before $zip->addFromString('word/document.xml', $xmlString);

It works on my Ubuntu 12.04

Don't forget to type your variable in same time when you create a docx file, I mean never type FIRST_AND_LAST_NAME and then you add a symbol $ after that. It creates different XML code.


Ok, I have used a class I found at phpclasses:

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

Here is the working code:

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();

    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜