Using Office Word to read doc files with PHP

2019-07-08 08:52发布

问题:

I am trying to use PHP with word.application to read a file. It simply will not open the file. It's echoing the right version.

$w = new COM("word.application") or die("Is office installed?");
echo 'Loaded Word, version ' . $w->Version . '<br>'; 
$w->Visible = false;

$w->Documents->Open(realpath('test.docx'));

$content = (string) $w->ActiveDocument->Content;

echo $content;

$w->Quit();
$w->Release();
$w = null;

I get the error:

Uncaught exception 'com_exception' with message 'Source: Microsoft Word
Description: This command is not available because no document is open.' 

It feels like it's some kind of permission problem. I tried to put the path of the test.docx besides using realpath and that did not help. Also tried to put it in the root of my C drive. I am using Windows 7 Professional and Microsoft Office 2007.

回答1:

Documents->Open returns a document if all is ok. Probably, the document does not exists (path incorrect), or you haven't got the rights to open it from PHP. Store the result in $var, check if it has an appropriate value (probably not isset, null or false if not), and use $var->Content to read the content.



回答2:

  1. Try doing a file_exists on said file/path.
  2. If that works, try file_get_contents and see if you can read it.

If that all works - then it's not a problem with permissions/etc.