Best way to dynamically create Word doc

Associate
Joined
18 Oct 2002
Posts
2,055
Location
Southend-on-Sea
I have a client with reports running on their intranet. These are produced using PHP to connect to the FoxPro backend. They're now wanting to be able to dynamically create Word documents from some of this data, specifically they want to generate client letters for quotation work on the system.

Ideally I'd like to have a template doc that will contain variables that can then be replaced with values from the database. The document should then be saved to the server with a unique name.

I've taken a look around and there seem to be several ways to achieve this. Does anyone here have experience of this and be able to recommend the best method?

I was looking at phpdocx which looks good, but its $90 for the version that supports templates and I'm reluctant to part with that without trying it first to ensure it meets my needs. Any other alternatives?

Don't mind coding it myself if that's needed but I'm hoping there is something already out there (free preferably!!) that can do this.

Thanks.
 
Old trick of mine...

Use HTML. Save as .doc.

Quick and dirty but worked in all currently used versions of Word last time I checked.
 
Yeah, I tried that. Only issue is that whenever someone tries to open the doc it asks to convert the file and you need to select HTML Document, I can live with that but my client won't like it. Also, images are not saved into the document.
 
Not had that issue myself.

Are you setting the content headers to MS Word?

Not sure how you would deal with images.
 
Yes, have the following:

header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");

So it saves as a .doc but Word asks to convert each time its opened. I'll look into it a bit further to find out why.

Cheers.
 
DOCX files are really ZIP files containing XML. If you re-name a DOCX file to ZIP you can un-zip the contents and check out the underlying XML. So if there is libraries in PHP for working with XML and ZIP you should be able to create a DOCX file.

I know you're not using .NET but http://www.microsoft.com/download/en/details.aspx?id=5124 (OpenXMLSDKTool.msi) comes with a tool that allows you to inspect DOCX files and see the underlying XML. http://www.ecma-international.org/publications/standards/Ecma-376.htm could be helpful as well.

Guess it is asking to convert because it is a HTML file and not a native Word document.

[EDIT]You could also dabble with Word 2003 XML: http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats. They get large though because they're uncompressed
 
Last edited:
Thanks for all your suggestions guys, most helpful and pointed me in some new directions. In the end I've used PHPWord, seems to do everything I need and very simple to setup. Still in beta but seems stable enough.
 
Back
Top Bottom