2011-05-18 60 views
1

假設我有MSWord文件source.doc,其中包含下一個內容「Microsoft Word文件的內容」。 例如,我想通過PHP打開它,並將「Microsoft」替換爲「Openoffice」,並將結果保存到result.doc。 下面是使用preg_replace代碼:PHP編輯Microsoft Word文檔str_replace和preg_replace不起作用

$content = file_get_contents(SOMEPATH . '/source.doc'); 
$new_content = preg_replace('/Microsoft/i', 'Openoffice', $content); 
file_put_contents(SOMEPATH . '/target.doc', $new_content); 

或者使用str_replace

$content = file_get_contents(SOMEPATH . '/source.doc'); 
$new_content = str_replace('Microsoft', 'Openoffice', $content); 
file_put_contents(SOMEPATH . '/target.doc', $new_content); 

他們沒有不起作用。代碼無任何例外運行,但target.docsource.doc相同。替換不執行。

我已經嘗試了很多不同的reciepts,比如正則表達式修飾符,iconv等,但沒有什麼幫助。

$content的顯示var_dumpsource.doc即充滿不尋常的字符和作爲我想一些它停止str_replacepreg_replace掃描的原始結構。無法弄清楚它是哪一個字符,如果我能找到它,該怎麼辦。

var_dump of $new_content與$ content相同。

感謝您的幫助!

+2

MS Word將其文件以壓縮格式保存,因此如果不先解壓縮,就無法查看或編輯內容。但即使你這樣做,你也必須知道文件格式的細節(有幾種),並且不能保證頁面上的文字被保存爲文件中的連續字符。 – Spudley 2011-05-18 14:07:30

回答

3

我認爲這是你正在尋找:) http://phpword.codeplex.com/什麼,因爲DOC文件都不是普通的文本文件(嘗試打開一個與notepad..you'll明白我的意思)

+1

請記住,PHPWord項目只允許您打開和操作DOCX文件(壓縮的openXML格式文件)。如果您需要處理舊的DOC格式,它將不起作用。 – DarinH 2011-05-18 18:25:39

10

如果你有一個DOCX文件需要替換一些東西,它基本上是一個壓縮的xml文檔。 下面是如何在DOCX文件中將「Microsoft」替換爲「Openoffice」的示例。

$zip = new ZipArchive; 
//This is the main document in a .docx file. 
$fileToModify = 'word/document.xml'; 
$wordDoc = "Document.docx"; 

if ($zip->open($wordDoc) === TRUE) { 
    //Read contents into memory 
    $oldContents = $zip->getFromName($fileToModify); 
    //Modify contents: 
    $newContents = str_replace('Microsoft', 'Openoffice', $oldContents); 
    //Delete the old... 
    $zip->deleteName($fileToModify); 
    //Write the new... 
    $zip->addFromString($fileToModify, $newContents); 
    //And write back to the filesystem. 
    $return =$zip->close(); 
    If ($return==TRUE){ 
     echo "Success!"; 
    } 
} else { 
    echo 'failed'; 
} 

希望這有助於!

+0

如果您還將源添加爲答案的鏈接,那將會很好。 – Magnilex 2015-01-02 20:01:26

+0

你是什麼意思?源代碼或其他來源的鏈接? – Shadymilkman01 2015-01-02 21:57:02

+0

啊,對不起。我誤解了答案。我以爲你找到了谷歌的答案。如果是這樣的話,鏈接到源代碼將是一件好事。無論如何,歡迎來到Stack Overflow。 – Magnilex 2015-01-02 22:02:01