2011-05-18 59 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