2010-08-25 16 views
1

因此,這裏是我的代碼:問題節省編輯zip壓縮包(DOCX)

<?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」字符串在docuemnt中)。

它在我的Lunux製作服務器上不起作用(「$ FIRST_AND_LAST_NAME」字符串仍然存在,沒有「John Doe」)。

沒有錯誤或通知,「ok」打印沒有任何錯誤。我確保test.docx文件的權限設置爲777.

+0

沒有警告?報告錯誤? close()返回true嗎? – 2010-08-25 14:11:43

+0

您是否嘗試過在$ xmlString被提取後查看內容?可能是提取在Linux方面的失敗。 str_replace不會讓你生氣,只是突然失敗,所以很可能它的輸入($ xmlString)不是你期望的那樣。 – 2010-08-25 14:12:16

+0

@Pekka我只注意到$ zip-> close()返回false。 – 2010-08-25 14:15:28

回答

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

    } 
} 
+0

好吧,我知道這是一個PHP 4舊類,但嘿,它的作品。我只需要現在就開始工作。我可以稍後重構。 – 2010-08-26 08:27:14

1

如果close()返回false,寫入歸檔時出錯。

使用getStatusString得到確切的錯誤信息。

+0

我得到'致命錯誤:調用未定義的方法ZipArchive :: getStatusString()'。看來服務器是PECL zip的舊版本。 – 2010-08-25 14:21:47

+0

@Richard aww。無法看到任何獲取錯誤消息的5.2.7版之前的方法...錯誤報告已完全打開? – 2010-08-25 14:24:01

+0

是的。我有error_reporting(E_ALL);在文件的頂部。 – 2010-08-25 14:26:36

1

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

我Ubuntu 12.04

當你創建一個docx文件時,不要忘記在同一時間輸入你的變量,我的意思是從來沒有輸入FIRST_AND_LAST_NAME,然後在那之後再添加一個符號$。它創建不同的XML代碼。