tags:

views:

328

answers:

3

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.

+1  A: 

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

fwrite($fp, $contents);

should be

fwrite($fp, $contents3);
Mike A.
thanks, I saw it, but that wasn't my problem :-( Still only see the contents of 1.doc
jsmb
A: 

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
+3  A: 

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
Good point! Never thought about that, I always work with .txts, never use .docs.
Psytronic
Tried aswell, it would only write the first doc file to the third
Psytronic
Ok thanks, I will have to find another way!
jsmb
What are you trying to do? Handling documents in PHP is a complex issue, maybe we can point you in the right direction.
Pekka
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