如何在php中修改.doc或.docx文件

时间:2010-07-21 09:36:04

标签: php tabs

我必须修改.doc中上传的.docxphp文件。我用谷歌搜索,但我只是发现了如何阅读,但不是这样。   我希望word文件不变,并将文本放在该MS Word文件的底部。  怎么可能有人知道请回复。

谢谢,


我使用了以下代码: -

$w='Test';
$fp = fopen('c:/text.doc', 'a+');
fwrite($fp, $w);
fclose($fp);

它附加了字符串但没有显示在word文档中。 当我将 doc 文件的扩展名更改为 xml 时,它会在结尾处显示字符串。 为什么不应该在doc文件中显示。

谢谢,

4 个答案:

答案 0 :(得分:3)

对于Docx文件,您可以轻松使用诸如TbsZip之类的zip阅读器来阅读和编辑主XML子文件(Docx文件实际上是zip存档文件)。对于DOC文件,它非常困难,因为它是一个二进制文件。

以下是使用TbsZip的代码示例:

<?php

$x = "Hello World!";

include_once('tbszip.php');

$zip = new clsTbsZip();

// Open the document
$zip->Open('mydoc.docx');
$content = $zip->FileRead('word/document.xml');
$p = strpos($content, '</w:body>');
if ($p===false) exit("Tag </w:body> not found in document.");

// Add the text at the end
$content = substr_replace($content, '<w:p><w:r><w:t>'.$x.'</w:t></w:r></w:p>', $p, 0);
$zip->FileReplace('word/document.xml', $content, TBSZIP_STRING);

// Save as a new file
$zip->Flush(TBSZIP_FILE, 'new.docx');

答案 1 :(得分:2)

DOCX格式的文档应该是XML(压缩),因此您可以尝试解析和修改它们......

有关格式的详细信息,请参阅here

答案 2 :(得分:0)

好吧,我建议将文件保存为XML。在MS Word中编写文档时,请另存为 - &gt;其他格式 - &gt;在这里选择XML。

您仍然可以在MS Word中打开文档,使用PHP DOM或SimpleXML编辑XML很容易。

要在底部添加一些文本,您只需要向XML正文添加一个新的w:p元素:

<w:p w:rsidR="00CF175F" w:rsidRDefault="00CF175F">
<w:r>
<w:t>New text to be added</w:t>
</w:r>
</w:p>

W是命名空间。对于Word 2007+,它是:

http://schemas.openxmlformats.org/wordprocessingml/2006/main

在较旧的XML格式中,有不同的名称空间,因此您必须查看MS网页才能找到正确的名称。

答案 3 :(得分:0)

我有同样的任务来编辑php中的 .doc .docx 文件,我已经使用了这个代码。

参考http://www.onlinecode.org/update-docx-file-using-php/

    $full_path = 'template.docx';
    //Copy the Template file to the Result Directory
    copy($template_file_name, $full_path);

    // add calss Zip Archive
    $zip_val = new ZipArchive;

    //Docx file is nothing but a zip file. Open this Zip File
    if($zip_val->open($full_path) == true)
    {
        // In the Open XML Wordprocessing format content is stored.
        // In the document.xml file located in the word directory.

        $key_file_name = 'word/document.xml';
        $message = $zip_val->getFromName($key_file_name);               

        $timestamp = date('d-M-Y H:i:s');

        // this data Replace the placeholders with actual values
        $message = str_replace("client_full_name",      "onlinecode org",       $message);
        $message = str_replace("client_email_address",  "ingo@onlinecode.org",  $message);
        $message = str_replace("date_today",            $timestamp,             $message);      
        $message = str_replace("client_website",        "www.onlinecode.org",   $message);      
        $message = str_replace("client_mobile_number",  "+1999999999",          $message);

        //Replace the content with the new content created above.
        $zip_val->addFromString($key_file_name, $message);
        $zip_val->close();
    }