我试图通过将文件读入变量来替换Word文档中的字符串 $content 然后使用 str_ireplace() 更改字符串。我可以从文件中读取内容,但 str_ireplace() 似乎无法替换字符串。我认为会是这样,因为根据 PHP 文档,该字符串是“二进制安全”的。抱歉,我是 PHP 文件操作的初学者,所以这一切对我来说都是新的。

这是我写的。

copy('jack.doc' , 'newFile.doc');
$handle = fopen('newFile.doc','rb');
$content = '';

while (!feof($handle))
{
    $content .= fread($handle, 1);
}
fclose($handle);

$handle = fopen('newFile.doc','wb');
$content = str_ireplace('USING_ICT_BOX', 'YOUR ICT CONTENT', $content);
fwrite($handle, $content);
fclose($handle);

当我下载新文件时,它会在 MS Word 中正常打开,但显示的是旧字符串,而不是应替换的字符串。

我可以解决这个问题吗?有没有更好的工具可以用来通过 PHP 替换 MS Word 中的字符串?

有帮助吗?

解决方案 4

我将选择 PHPWord www.phpword.codeplex.com,因为我相信教师明年将获得 Office 2007,而且我将尝试找到一些通过 PHP 在 .docx 和 .doc 之间进行转换的方法,以支持他们在与此同时。

其他提示

我对编辑有同样的要求 .doc 或者 .docx 使用 php 文件,我已经找到了解决方案。我已经写了一篇关于它的文章:: http://www.onlinecode.org/update-docx-file-using-php/

copy('jack.doc' , 'newFile.doc');
$full_path =  'newFile.doc';
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();
}

也许这会为您指明正确的方向: http://davidwalsh.name/read-pdf-doc-file-php

到目前为止我找到的解决方案(虽然未经测试):
多克弗特 - 适用于 Doc,免费,但不能直接使用
PHPWordLib - 适用于 Doc,不是免费的
PHPDocX - 仅 DocX,需要 Zend。

如果您可以访问网络服务,请查看 多克莫西斯 云服务,因为它可以将 doc 文件与您的数据进行邮件合并,并返回 doc/pdf/其他文件。您可以通过 https post 到服务来发出请求,因此从 PHP 中转发非常简单。

Linux上处理word文档文件的方法有很多种

  1. antiword - 转换为纯文本时效率不高。
  2. pyODconvert
  3. open-office 或者 liboffice - 通过联合国组织
  4. unoconv 实用程序 - 需要在服务器上安装权限

有一个 python 脚本最适用于在线文件转换,但您需要通过命令行转换这些文件。

仅使用php代码处理word文件还没有具体且令人满意的解决方案。

我寻找了很长时间才得到这个建议。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top