Categories
PHP

Read a Word doc using COM

So I managed to write a script to read a Microsoft Word document using PHP CLI and the COM object pretty easily, but then battled to get it working in the browser.

In your php.ini:

; allow Distributed-COM calls
;
http://php.net/com.allow-dcom
com.allow_dcom =
true

On your Windows PC:

  1. Run “dcomcnfg” (right-click Windows icon and select Run) to open Component Services
  2. Open Component Services » Computers » My Computer » DCOM Config
  3. Search for Microsoft Office Word 97-2003 Document (it will be something like this translated to your language, so take a while and search for it)
  4. Right-click on it and open the properties
  5. Choose the “Identity” tab
  6. Normally this is set to “the launching user”. You have to change this to “the interactive user” or an admin user of your choice.
  7. Apply these new settings and test your COM application. It should work fine now.

http://forums.phpfreaks.com/topic/191034-word-com-object-throwing-exception/

<?php
echo '<pre>';
echo "starting\n";
set_time_limit (30);

//to allow time for Word to load.

$word = new COM("word.application") or die ("Could not initialise MS Word object.");
echo "COM instantiated\n";
$word->Application->Visible = False;
echo "set visibility to false\n";

$doc = 'test.doc';
$document = realpath($doc);

	if (!is_readable($document)) {
		echo "Document is not readable\n";
		die();
	} elseif(!is_file($document)) {
		echo "Document does not exist\n"; die();
	}

echo "Document exists and is readable \n";
$word->Documents->Open( $document );
echo "Document opened\n";

// Extract content.
$content = $word->ActiveDocument->Content;

echo "test\n----------\n";
print_r($content);
echo "test\n----------\n";
echo "Extracting string value of content\n";

$content = (string) $content;
echo "test\n----------\n";
echo $content;
echo "test\n----------\n";
echo $content;

$word->ActiveDocument->Close(false);
echo "Closed Document\n";
$word->Quit();
echo "Quit Word \n";
$word = null;
unset($word);
echo '</pre>';

Adapted from this example (with loads of sloppy syntax errors): http://www.tek-tips.com/viewthread.cfm?qid=1692863

By foxbeefly

PHP / MySQL Developer

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.