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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Good point! Never thought about that, I always work with .txts, never use .docs.
Tried aswell, it would only write the first doc file to the third
What are you trying to do? Handling documents in PHP is a complex issue, maybe we can point you in the right direction.
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 setasign.de/products/pdf-php-solutions/fpdi/demos/… I can combine the pdf's. (and now I'm having other problems... maximum time exceed thingies..) ;-) Thanks for helping.
1

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

fwrite($fp, $contents);

should be

fwrite($fp, $contents3);

1 Comment

thanks, I saw it, but that wasn't my problem :-( Still only see the contents of 1.doc
-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.";
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.