本文主要和大家分享 PHP使用COM組件轉換word文檔為HTML並實現線上預覽,希望能協助到大家。
PHP5.4
[CoM];
path to a file containing GUlDs,llDs or filenames of files with TypeLibs;
http://php.net/com.typelib-file;com.typelib_file=
;allow Distributed-COM calls
;http://php.cn/com.allow-dcomcom.allow dcom= true
PHP7.0
在php.ini中增加
[COM_DOT_NET]extension=php_com_dotnet.dll
重啟 php即可.
在根目錄輸入
<?php
error_reporting(E_ALL);
ini_set("display_errors","On");
$excel = new COM("Excel.application") or die ("ERROR: Unable to instantaniate COM!\r\n");
print_r(get_loaded_extensions());?>
可以數組形式羅列php的現有組件.
執行程式
建立index.php, 預設傳入3.doc , 然後運行就可以查看效果了.
<?php/**
* Created by PhpStorm.
* User: zhangcanlong
* Date: 2016/11/15
* Time: 23:41
*/function word2html($wordname,$htmlname){
//擷取連結地址
/*
//$url=$_SERVER['HTTP_HOST'];//擷取伺服器位址
// $url=$url.$_SERVER['PHP_SELF'];//擷取當前伺服器下的檔案名稱和目錄
// $url=dirname($url)."/";
*/
//去除目錄中的檔案名稱
$word = new COM("word.application") or die("找不到 Word 程式"); // 建立一個指向新COM組件的索引
// 顯示目前正在使用的Word的版本號碼
//echo "Loading Word, v. {$word->Version}<br>";
// 把它的可見度設定為0(假),如果要使它在最前端開啟,使用1(真)
$word->Visible = 0;
$word->Documents->Open($wordname) or die("無法開啟這檔案");
header("Content-Type: text/html;charset=gb2312");//設定檔案的格式
//開啟一個文檔
//把文檔儲存在目錄中
try{
$word->Documents[1]->SaveAs($htmlname,8);
} catch(Exception $e){
print $e->getMessage();
}
$content=file_get_contents($htmlname);
echo $content;//輸出word文檔的內容
// 關閉與COM組件之間的串連
$word->Quit();
unset($word);
}
$fileName = '3.doc';
$wordName = explode('.',$fileName)[0];$wordExt = explode('.',$fileName)[1];//擷取當前檔案下的目錄
$file_Name=dirname(__FILE__);
if (is_file($wordName.'.html')) {
echo file_get_contents($wordName.'.html');
}else{
word2html("$file_Name\\".$wordName.".".$wordExt,"$file_Name\\".$wordName.".html");//要轉換的word檔案和轉換成的html的檔案名稱}
可以看到目前的目錄的1.docx會產生1.html檔案,另外網站展示1.html