开发者

Add Word document to another Word document with PHP

How can I add a Word document to another Word document with PHP (fwrite)?

$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开发者_如何学JAVA($fp, $contents); 

3.doc only contains 1.doc.


First of all, you're only actually fwriting() the $contents variable, not $contents3.

The real problem though will be that the internal structure of a Word document is more complex. A Word document contains a certain amount of preamble and wrapping. If you simply concatenate two Word documents, you'll probably* only be left with a garbage file. 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.

*) Tested it just for the fun of it, Word indeed can't do anything with a file made of two concatenated .doc files.


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

$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.";
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜