$file='C:/a.doc';
$saveas=__DIR__.'/tmp/a.html';
$word=new COM('word.application');
$document=$word->Documents->Open($file);
$document->SaveAs($saveas,8);
$word->Quit();
$word=null;
echo file_get_contents($saveas);
@unlink($saveas);
它在 PHP CLI 模式下运行良好(php -f "com_server.php"),但是当我通过 web(windows/apache http://localhost/com_server.php )运行它时,出现错误:
Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `word.application': Server execution failed' in D:\www\wwwroot\com_server.php:16 Stack trace: #0 D:\www\wwwroot\com_server.php(16): com->com('word.applicatio...') #1 {main} thrown in D:\www\wwwroot\com_server.php on line 16
我也试过将代码包装在 shell_exec 中,但同样的错误。
有什么建议吗?
最佳答案
我猜第 16 行是来自 SaveAs()
的那一行:
$document=$word->Documents->Open($file);
$document->SaveAs($saveas,8);
正如您在评论中所说
有时 $word->Documents->Open()
会给出该错误;如果您之前打开过它,请尝试使用类似 $word->ActiveDocument
的内容,或者尝试:
$word->Documents->Add()
$word->ActiveDocument->open()
然后,尝试保存语句。看起来你没能正确打开它。我已经有一段时间没有测试过了,所以试一试。另外,请记住不要在诸如 print
之类的句子中留下括号(但要用大括号),并在完成后将对象置空。
如果这两个都不起作用,请检查 this page有关 Word 的 expression.SaveAs2
方法的详细说明。也许它会有所帮助。祝你好运。
关于PHP 使用 COM 将 word 转换为 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3351306/