I was recently working on an enterprise project in which I needed to detect the text inside a Word Document. Now, I could have got rid of all the non-standard characters from the .doc file and hoped I got something reasonable at the end. I could have tried to run Word 2007 via command line to save the file as a .docx. Or I could just talk to any copy of MS Word via COM and have it do all the dirty work for me.
Naturally, I chose the latter. Here’s ten lines of code that do just that.
Communicating via COM in PHP is easy as ever; especially for people coming from a VB background where executing complex tasks in MS-applications is a piece of cake, you will feel right at home in PHP. In fact, VB COM calls can be converted to PHP COM calls in just a few simple search and replaces.
Without further ado, here’s the code. I’ll point out a gotcha I noticed in just a moment.
<?php $word = new COM("word.application") or die ("Could not initialise MS Word object."); $word->Documents->Open(realpath("Sample.doc")); // Extract content. $content = (string) $word->ActiveDocument->Content; echo $content; $word->ActiveDocument->Close(false); $word->Quit(); $word = null; unset($word);
We first create a new COM object of word.application, which provides access to core MS Word functionality. We then tell it to open “Sample.doc” in the current directory. There’s a bit of a bug/feature when trying to get the content out, however. If you debug this code, you’ll find that $word->ActiveDocument->Content is an empty object (variant). If you assign the value to a variable you’ll get an empty string, as the variant object has no real __toString(). The workaround in PHP is to explicitly type cast the value as a string and make PHP/COM take care of finding the real value. If you try this in a VB macro run inside Word, this is not neccessary – a MsgBox(ActiveDocument.Content) works fine.
We also need to be aware of performance considerations on Windows servers – creating a COM object initialises a fully-fledged instance of WINWORD.exe, and a 10-15MB memory footprint associated with it. We first call the Quit() method on the Word COM object, then null the variable and destroy it to be safe. Watch your task manager while running this script and you’ll notice WINWORD.exe appears briefly then exits.
So, in just ten lines of code you can get the text out of an MS Word document, easy as ever!
If you want to explore this approach further, load up MS Word and open the Visual Basic Script Editor – press Alt+F11, then F2. (If that doesn’t work, Tools > Macros > Visual Basic Script Editor, or “Visual Basic” under the Developer tab 2007, then press F2.) From the library drop-down box in the “Object Browser” – which might say “