PHP编辑Microsoft Word文档str_replace和preg_replace不起作用 [英] PHP editing Microsoft Word document str_replace and preg_replace don't work

查看:129
本文介绍了PHP编辑Microsoft Word文档str_replace和preg_replace不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设,我有MSWord文件source.doc,下一个内容为"Microsoft Word文件的内容". 例如,我想通过PHP打开它,并将单词"Microsoft"替换为"Openoffice",然后将结果保存到 result.doc 中. 这是使用preg_replace的代码:

Assume, I've got MSWord file source.doc with next content "Content of Microsoft Word file". For example, I'd like to open it via PHP and replace word "Microsoft" to "Openoffice" and save the result into result.doc. Here is the code using 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.doc source.doc 相同.替换无法执行.

None of them doesn't work. Code runs without any exceptions, but target.doc is the same as source.doc. Replacement not performs.

我尝试了很多不同的接收方式,例如正则表达式修饰符,iconv等,但是没有帮助.

I've tried a lot of different reciepts, such as regular expression modificators, iconv and so on, but nothing helps.

var_dump显示了 source.doc 的原始结构,该结构充满了不寻常的字符,并且我想其中的一些会停止str_replacepreg_replace扫描.无法找出它是哪一个字符,如果找到它该怎么办.

var_dump of $content shows raw structure of source.doc that is full of unusual characters and as I suppose some of it stops str_replace or preg_replace scanning. Can't figure out which char is it and what should I do if I'll find it.

var_dump与$ content相同.

var_dump of $new_content is identical to $content.

感谢您的帮助!

推荐答案

如果您有DOCX文件,则需要替换其中的内容,它基本上是一个压缩的xml存档. 这是一个有关如何在DOCX文件中将"Microsoft"替换为"Openoffice"的示例.

If you have a DOCX file you need to replace something in, its basically a zipped up xml archive. Here's an example on how to replace the word "Microsoft" with "Openoffice" in a DOCX file.

$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';
}

希望这会有所帮助!

这篇关于PHP编辑Microsoft Word文档str_replace和preg_replace不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆