简体   繁体   English

使用PHP将Word文档添加到另一个Word文档

[英]Add Word document to another Word document with PHP

How can I add a Word document to another Word document with PHP (fwrite)? 如何使用PHP(fwrite)将Word文档添加到另一个Word文档中?

$filename = "./1.doc"; 
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename)); 

$filename2 = "./2.doc";
$handle2 = fopen($filename2, "r");
$contents2 = fread($handle2, filesize($filename2)); 

$contents3 =$contents2.$contents;
$fp = fopen("./3.doc", 'w+'); 

fwrite($fp, $contents); 

3.doc only contains 1.doc. 3.doc仅包含1.doc。

First of all, you're only actually fwriting() the $contents variable, not $contents3 . 首先,您实际上只是fwriting() $contents变量,而不是$contents3

The real problem though will be that the internal structure of a Word document is more complex. 但是,真正的问题是Word文档的内部结构更加复杂。 A Word document contains a certain amount of preamble and wrapping. Word文档包含一定数量的序言和换行。 If you simply concatenate two Word documents, you'll probably * only be left with a garbage file. 如果你简单地连接两个Word文档,你 可能 *只留下一个垃圾文件。 You would need a library that can parse Word files, extract only the actual text content, concatenate the text and save it as a new Word file. 您需要一个可以解析Word文件,仅提取实际文本内容,连接文本并将其另存为新Word文件的库。

*) Tested it just for the fun of it, Word indeed can't do anything with a file made of two concatenated .doc files. *)仅出于乐趣的目的对其进行了测试,Word确实不能对由两个串联的.doc文件组成的文件执行任何操作。

Looks like you have a typo in your code on the last line: 看起来您在最后一行的代码中有错别字:

fwrite($fp, $contents);

should be 应该

fwrite($fp, $contents3);

I wouldn't bother with fopen for the first two, just file_get_contents(), then fopen 3.doc and write to it that way 我不会为前两个烦恼fopen,只是file_get_contents(),然后fopen 3.doc并以这种方式写入

$file1 = (is_file("./1.doc"))?file_get_contents("./1.doc"):"";
$file2 = (is_file("./2.doc"))?file_get_contents("./2.doc"):"";
$file3_cont = $file1.$file2;

if(is_file("./3.doc")){
  if(($fp = @fopen("./3.doc", "w+")) !== false){
    if(fwrite($fp, $file3_cont) !== false){
     echo "File 3 written.";
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM