0

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($fp, $contents); 

3.doc only contains 1.doc.

Todd Main
  • 28,951
  • 11
  • 82
  • 146
jsmb
  • 1
  • 1

3 Answers3

3

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.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Good point! Never thought about that, I always work with .txts, never use .docs. – Psytronic Oct 19 '09 at 08:49
  • Tried aswell, it would only write the first doc file to the third – Psytronic Oct 19 '09 at 08:58
  • What are you trying to do? Handling documents in PHP is a complex issue, maybe we can point you in the right direction. – Pekka Oct 19 '09 at 10:35
  • I'm working on a mailmerge, I accomplished this with livedocx, works great. (nusoap and php5) but now I have to combine several documents into one. But I found a solution. With livedocx you can safe the document as a pdf and with http://www.setasign.de/products/pdf-php-solutions/fpdi/demos/concatenate-fake/ I can combine the pdf's. (and now I'm having other problems... maximum time exceed thingies..) ;-) Thanks for helping. – jsmb Oct 19 '09 at 14:04
1

Looks like you have a typo in your code on the last line:

fwrite($fp, $contents);

should be

fwrite($fp, $contents3);
Mike A.
  • 398
  • 3
  • 12
  • thanks, I saw it, but that wasn't my problem :-( Still only see the contents of 1.doc – jsmb Oct 19 '09 at 08:53
-1

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.";
    }
  }
}
Psytronic
  • 6,043
  • 5
  • 37
  • 56