五月综合缴情婷婷六月,色94色欧美sute亚洲线路二,日韩制服国产精品一区,色噜噜一区二区三区,香港三级午夜理伦三级三

您現(xiàn)在的位置: 365建站網(wǎng) > 365文章 > PHP中讀取,寫入和導(dǎo)出WORD文檔的代碼總結(jié)

PHP中讀取,寫入和導(dǎo)出WORD文檔的代碼總結(jié)

文章來源:365jz.com     點(diǎn)擊數(shù):983    更新時(shí)間:2017-08-29 11:18   參與評(píng)論
如果直接用FILE后者OPEN等函數(shù)讀取WORD的話往往是亂碼,原來要使用COM 這是我簡(jiǎn)單的一個(gè)讀取并存儲(chǔ)到新的WORD上的文件

一、先開啟php.ini的COM,操作如下

1.

extension=php_com_dotnet.dll

2.

com.allow_dcom = true

二、開啟之后就可以試下如下操作

1、建立一個(gè)指向新COM組件的索引

$word = new COM("word.application") or die("Can't start Word!");

2、顯示目前正在使用的Word的版本號(hào)

echo "Loading Word, v. {$word->Version}";

3、把它的可見性設(shè)置為0(假),如果要使它在最前端打開,使用1(真)

$word->Visible = 0;

4、打開一個(gè)文檔

$word->Documents->open(dirname(__FILE__)."/1.doc");

5、讀取文檔內(nèi)容

$test= $word->ActiveDocument->content->Text;

6、輸出文檔內(nèi)容

echo $test;

更多關(guān)于PHP中讀取,寫入和導(dǎo)出WORD文檔的代碼總結(jié)如下:

1.使用COM組件

<?  
// 建立一個(gè)指向新COM組件的索引  
$word = new COM(”word.application”) or die(”Can't start Word!”);  
// 顯示目前正在使用的Word的版本號(hào)  
//echo “Loading Word, v. {$word->Version}<br>”;  
// 把它的可見性設(shè)置為0(假),如果要使它在最前端打開,使用1(真)  
// to open the application in the forefront, use 1 (true)  
//$word->Visible = 0;  

//打?一個(gè)文檔  
$word->Documents->OPen(”d:\myweb\muban.doc”);  
//讀取文檔內(nèi)容  

$test= $word->ActiveDocument->content->Text;  

echo $test;  
echo “<br>”;  
//將文檔中需要換的變量更換一下  
$test=str_replace(”<{變量}>”,”這是變量”,$test);  
echo $test;  
$word->Documents->Add();  
// 在新文檔中添加文字  
$word->Selection->TypeText(”$test”);  
//把文檔保存在目錄中  
$word->Documents[1]->SaveAs(”d:/myweb/comtest.doc”);  
// 關(guān)閉與COM組件之間的連接  
$word->Quit();  
?> 
2.比較簡(jiǎn)潔的一種方法,且可跨平臺(tái)

以下為詳細(xì)代碼:

class.word.php

<?php
class Word{
  function start(){
    ob_start(); //打開輸出控制緩沖
    echo '<html xmlns:o="urn:schemas-microsoft-com:office:office"';
    echo 'xmlns:w="urn:schemas-microsoft-com:office:word"';
    echo 'xmlns="http://www.w3.org/TR/REC-html40">';
  }
  function save($path){
    echo "</html>";
    $data=ob_get_contents(); //返回輸出緩沖區(qū)的內(nèi)容
    ob_end_clean(); //清空緩沖區(qū)并關(guān)閉輸出緩沖
    $this->writeFile($path,$data); //將緩沖區(qū)內(nèi)容寫入word
  }
  function writeFile($fn,$data){
    $fp=fopen($fn,"wb+");
    fwrite($fp,$data);
    fclose($fp);
  }
}

index.php

<?php
include("class.word.php");
$word=new Word();
$word->start();
//以下內(nèi)容會(huì)保存在WORD文件中,可以使用HTML標(biāo)簽
?>
 <h1>直接用php創(chuàng)建word文檔</h1>
 作者:axgle
<hr size=1>
 <p>如果你打開data.doc,看到了這里的介紹,則說明word文檔創(chuàng)建成功了。
<p>
不論是在什么操作系統(tǒng)下,使用本方法都可以直接用PHP生成word文檔。絕對(duì)不是吹牛!
就算是沒有安裝word,也能夠生成word文件。
當(dāng)然了,生成的word文件可以用word,wps或者其他軟件打開。
<p>
<b>使用方法:</b>
<br>
首先用$word->start()表示要生成word文件了。
然后你可以輸出任何的HTML代碼,不論是從文件讀過來再寫到這里,
還是直接在這里輸出HTML,都沒有關(guān)系。
<p>等你輸出完畢后,用$word->save($path)方法,其中$path是你想
生成的word文件的名稱(可以給出完整的路徑).當(dāng)你使用了$word->save()
方法后,這后面的任何輸出都和word文件沒有關(guān)系了,也就是說word的生成
工作就完成了。之后就和你平常使用php的方式一樣拉。隨便你輸出什么東西,
都直接在瀏覽器里輸出,而不會(huì)寫到word里面去。
<p>這是本人想到的一個(gè)很有意思的方法,它的實(shí)現(xiàn)方法出人意料的簡(jiǎn)單,并且避免
了對(duì)windows環(huán)境的依賴。
<br>哈哈,很有意思吧?享受它吧!
<hr size=1>
<?php
//以上內(nèi)容會(huì)保存在WORD文件中
$word->save("data.doc");//保存word并且結(jié)束.
//以下內(nèi)容正常輸出在頁(yè)面文件中
header("Content-type:text/html;charset=utf-8");
echo 'data.doc生成成功,請(qǐng)到目錄下查看<br>';
?>

3.通過baihui網(wǎng)API實(shí)現(xiàn)讀取word文檔并展示

可以 使用API 可以看看baihui.com 的寫寫應(yīng)用 的API

申請(qǐng)一個(gè) APPKEY 就能使用,你可以看看 ... 對(duì)免費(fèi)版本有限制

比如 excel 支持,可以參考我這個(gè) appkey是我申請(qǐng)的,可以使用吧 ...
保存成本地的一個(gè)html文件 打開后直接使用

word 的類似

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>測(cè)試百會(huì)格格遠(yuǎn)程API</title>
</head>
<body>
<form action="http://gege.baihui.com/remotedoc.im?apikey=079c6475174c7a46351260ed35e54ecd&output=editor" target="_self" enctype="multipart/form-data" method="post">
上傳文件: <input type="file" name="content" site="38"/>
<input type="hidden" name="filename" value="my.xls,my.xlsx" />
<input type="hidden" name="saveurl" value="http://vai.com" />
<input type="hidden" name="id" value="21012145" />
<input type="hidden" name="format" value="xlsx" />
<input type="hidden" name="persistence" value="true" />
<input type="submit" value="提交" />
</form>
</body>
</html>


4.使用PHP導(dǎo)出Word文檔的原理和實(shí)例
 

原理

 一般,有2種方法可以導(dǎo)出doc文檔,一種是使用com,并且作為php的一個(gè)擴(kuò)展庫(kù)安裝到服務(wù)器上,然后創(chuàng)建一個(gè)com,調(diào)用它的方法。安裝過office的服務(wù)器可以調(diào)用一個(gè)叫word.application的com,可以生成word文檔,不過這種方式我不推薦,因?yàn)閳?zhí)行效率比較低(我測(cè)試了一下,在執(zhí)行代碼的時(shí)候,服務(wù)器會(huì)真的去打開一個(gè)word客戶端)。理想的com應(yīng)該是沒有界面的,在后臺(tái)進(jìn)行數(shù)據(jù)轉(zhuǎn)換,這樣效果會(huì)比較好,但是這些擴(kuò)展一般需要收費(fèi)。
第2種方法,就是用PHP將我們的doc文檔內(nèi)容直接寫入一個(gè)后綴為doc的文件中即可。使用這種方法不需要依賴第三方擴(kuò)展,而且執(zhí)行效率較高。
 word本身的功能還是很強(qiáng)大的,它可以打開html格式的文件,并且能夠保留格式,即使后綴為doc,它也能識(shí)別正常打開。這就為我們提供了方便。但是有一個(gè)問題,html格式的文件中的圖片只有一個(gè)地址,真正的圖片是保存在其他地方的,也就是說,如果將HTML格式寫入doc中,那么doc中將不能包含圖片。那我們?nèi)绾蝿?chuàng)建包含圖片的doc文檔呢?我們可以使用和html很接近的mht格式。
mht格式和html很類似,只不過在mht格式中,外部鏈接進(jìn)來的文件,比如圖片、Javascript、CSS會(huì)被base64進(jìn)行編碼存儲(chǔ)。因此,單個(gè)mht文件就可以保存一個(gè)網(wǎng)頁(yè)中的所有資源,當(dāng)然,相比html,它的尺寸也會(huì)比較大。
mht格式能被word識(shí)別嗎?我將一個(gè)網(wǎng)頁(yè)保存成mht,然后修改后綴名為doc,再用word打開,OK,word也可以識(shí)別mht文件,并且可以顯示圖片。
好了,既然doc可以識(shí)別mht,下面就是考慮如何將圖片放入mht了。由于html代碼中的圖片的地址都是寫在img標(biāo)簽的src屬性中,因此,只要提取html代碼中的src屬性值,就可以獲得圖片地址。當(dāng)然,有可能您獲取到的是相對(duì)路徑,沒關(guān)系,加上URL的前綴,改成絕對(duì)路徑就可以了。有了圖片地址,我們就可以通過file_get_content函數(shù)獲取到圖片文件的具體內(nèi)容,然后調(diào)用base64_encode函數(shù)將文件內(nèi)容編碼成base64編碼,最后插入到mht文件的合適位置即可。
最后,我們有兩種方法將文件發(fā)送給客戶端,一種是先在服務(wù)器端生成一個(gè)doc文檔,然后將這個(gè)doc文檔的地址記錄下來,最后,通過header("location:xx.doc");就可以讓客戶端下載這個(gè)doc。還有一種是直接發(fā)送html請(qǐng)求,修改HTML協(xié)議的header部分,將它的content-type設(shè)置為application/doc,將content-disposition設(shè)置為attachment,后面跟上文件名,發(fā)送完html協(xié)議以后,直接將文件內(nèi)容發(fā)送給客戶端,也可以讓客戶端下載到這個(gè)doc文檔。

實(shí)現(xiàn)

通過以上的原理介紹,相信大家應(yīng)該對(duì)實(shí)現(xiàn)的過程有個(gè)初步的了解了,下面我給出一個(gè)導(dǎo)出函數(shù),這個(gè)函數(shù)可以將HTML代碼導(dǎo)出成一個(gè)mht文檔,參數(shù)有3個(gè),其中后2個(gè)為可選參數(shù)
content:要轉(zhuǎn)換的HTML代碼
absolutePath: 如果HTML代碼中的圖片地址都是相對(duì)路徑,那么這個(gè)參數(shù)就是HTML代碼中缺少的絕對(duì)路徑。
isEraseLink:是否去掉HTML代碼中的超鏈接
返回值為mht的文件內(nèi)容,您可以通過file_put_content將它保存成后綴名為doc的文件
這個(gè)函數(shù)的主要功能其實(shí)就是分析HTML代碼中的所有圖片地址,并且依次下載下來。獲取到了圖片的內(nèi)容以后,調(diào)用MhtFileMaker類,將圖片添加到mht文件中。具體的添加細(xì)節(jié),封裝在MhtFileMaker類中了。

 

/**
 * 根據(jù)HTML代碼獲取word文檔內(nèi)容
 * 創(chuàng)建一個(gè)本質(zhì)為mht的文檔,該函數(shù)會(huì)分析文件內(nèi)容并從遠(yuǎn)程下載頁(yè)面中的圖片資源
 * 該函數(shù)依賴于類MhtFileMaker
 * 該函數(shù)會(huì)分析img標(biāo)簽,提取src的屬性值。但是,src的屬性值必須被引號(hào)包圍,否則不能提取
 * 
 * @param string $content HTML內(nèi)容
 * @param string $absolutePath 網(wǎng)頁(yè)的絕對(duì)路徑。如果HTML內(nèi)容里的圖片路徑為相對(duì)路徑,那么就需要填寫這個(gè)參數(shù),來讓該函數(shù)自動(dòng)填補(bǔ)成絕對(duì)路徑。這個(gè)參數(shù)最后需要以/結(jié)束
 * @param bool $isEraseLink 是否去掉HTML內(nèi)容中的鏈接
* by theartemis.cn
 */
function getWordDocument( $content , $absolutePath = "" , $isEraseLink = true )
{
    $mht = new MhtFileMaker();
    if ($isEraseLink)
        $content = preg_replace('/<a\s*.*?\s*>(\s*.*?\s*)<\/a>/i' , '$1' , $content);   //去掉鏈接
       $images = array();
    $files = array();
    $matches = array();
    //這個(gè)算法要求src后的屬性值必須使用引號(hào)括起來
    if ( preg_match_all('/<img[.\n]*?src\s*?=\s*?[\"\'](.*?)[\"\'](.*?)\/>/i',$content ,$matches ) )
    {
        $arrPath = $matches[1];
        for ( $i=0;$i<count($arrPath);$i++)
        {
            $path = $arrPath[$i];
            $imgPath = trim( $path );
            if ( $imgPath != "" )
            {
                $files[] = $imgPath;
                if( substr($imgPath,0,7) == 'http://')
                {
                    //絕對(duì)鏈接,不加前綴
                }
                else
                {
                    $imgPath = $absolutePath.$imgPath;
                }
                $images[] = $imgPath;
            }
        }
    }
    $mht->AddContents("tmp.html",$mht->GetMimeType("tmp.html"),$content);

    for ( $i=0;$i<count($images);$i++)
    {
        $image = $images[$i];
        if ( @fopen($image , 'r') )
        {
            $imgcontent = @file_get_contents( $image );
            if ( $content )
                $mht->AddContents($files[$i],$mht->GetMimeType($image),$imgcontent);
        }
        else
        {
            echo "file:".$image." not exist!<br />";
        }
    }

    return $mht->GetFile();
}

 

 

 

使用方法:

 

$fileContent = getWordDocument($content,"http://theartemis.cn/Music/etc/");
$fp = fopen("test.doc", 'w');
fwrite($fp, $fileContent);
fclose($fp);

 

其中,$content變量應(yīng)該是HTML源代碼,后面的鏈接應(yīng)該是能填補(bǔ)HTML代碼中圖片相對(duì)路徑的URL地址
注意,在使用這個(gè)函數(shù)之前,您需要先包含類MhtFileMaker,這個(gè)類可以幫助我們生成Mht文檔。

 

<?php
/***********************************************************************
Class:        Mht File Maker
Version:      1.2 beta
Author:       Wudi <wudicgi@yahoo.de>
Description:  The class can make .mht file.
***********************************************************************/
class MhtFileMaker{
    var $config = array();
    var $headers = array();
    var $headers_exists = array();
    var $files = array();
    var $boundary;
    var $dir_base;
    var $page_first;
    function MhtFile($config = array()){
    }
    function SetHeader($header){
        $this->headers[] = $header;
        $key = strtolower(substr($header, 0, strpos($header, ':')));
        $this->headers_exists[$key] = TRUE;
    }
    function SetFrom($from){
        $this->SetHeader("From: $from");
    }
    function SetSubject($subject){
        $this->SetHeader("Subject: $subject");
    }
    function SetDate($date = NULL, $istimestamp = FALSE){
        if ($date == NULL) {
            $date = time();
        }
        if ($istimestamp == TRUE) {
            $date = date('D, d M Y H:i:s O', $date);
        }
        $this->SetHeader("Date: $date");
    }
    function SetBoundary($boundary = NULL){
        if ($boundary == NULL) {
            $this->boundary = '--' . strtoupper(md5(mt_rand())) . '_MULTIPART_MIXED';
        } else {
            $this->boundary = $boundary;
        }
    }
    function SetBaseDir($dir){
        $this->dir_base = str_replace("\\", "/", realpath($dir));
    }
    function SetFirstPage($filename){
        $this->page_first = str_replace("\\", "/", realpath("{$this->dir_base}/$filename"));
    }
    function AutoAddFiles(){
        if (!isset($this->page_first)) {
            exit ('Not set the first page.');
        }
        $filepath = str_replace($this->dir_base, '', $this->page_first);
        $filepath = 'http://mhtfile' . $filepath;
        $this->AddFile($this->page_first, $filepath, NULL);
        $this->AddDir($this->dir_base);
    }
    function AddDir($dir){
        $handle_dir = opendir($dir);
        while ($filename = readdir($handle_dir)) {
            if (($filename!='.') && ($filename!='..') && ("$dir/$filename"!=$this->page_first)) {
                if (is_dir("$dir/$filename")) {
                    $this->AddDir("$dir/$filename");
                } elseif (is_file("$dir/$filename")) {
                    $filepath = str_replace($this->dir_base, '', "$dir/$filename");
                    $filepath = 'http://mhtfile' . $filepath;
                    $this->AddFile("$dir/$filename", $filepath, NULL);
                }
            }
        }
        closedir($handle_dir);
    }
    function AddFile($filename, $filepath = NULL, $encoding = NULL){
        if ($filepath == NULL) {
            $filepath = $filename;
        }
        $mimetype = $this->GetMimeType($filename);
        $filecont = file_get_contents($filename);
        $this->AddContents($filepath, $mimetype, $filecont, $encoding);
    }
    function AddContents($filepath, $mimetype, $filecont, $encoding = NULL){
        if ($encoding == NULL) {
            $filecont = chunk_split(base64_encode($filecont), 76);
            $encoding = 'base64';
        }
        $this->files[] = array('filepath' => $filepath,
                               'mimetype' => $mimetype,
                               'filecont' => $filecont,
                               'encoding' => $encoding);
    }
    function CheckHeaders(){
        if (!array_key_exists('date', $this->headers_exists)) {
            $this->SetDate(NULL, TRUE);
        }
        if ($this->boundary == NULL) {
            $this->SetBoundary();
        }
    }
    function CheckFiles(){
        if (count($this->files) == 0) {
            return FALSE;
        } else {
            return TRUE;
        }
    }
    function GetFile(){
        $this->CheckHeaders();
        if (!$this->CheckFiles()) {
            exit ('No file was added.');
        } //theartemis.cn
        $contents = implode("\r\n", $this->headers);
        $contents .= "\r\n";
        $contents .= "MIME-Version: 1.0\r\n";
        $contents .= "Content-Type: multipart/related;\r\n";
        $contents .= "\tboundary=\"{$this->boundary}\";\r\n";
        $contents .= "\ttype=\"" . $this->files[0]['mimetype'] . "\"\r\n";
        $contents .= "X-MimeOLE: Produced By Mht File Maker v1.0 beta\r\n";
        $contents .= "\r\n";
        $contents .= "This is a multi-part message in MIME format.\r\n";
        $contents .= "\r\n";
        foreach ($this->files as $file) {
            $contents .= "--{$this->boundary}\r\n";
            $contents .= "Content-Type: $file[mimetype]\r\n";
            $contents .= "Content-Transfer-Encoding: $file[encoding]\r\n";
            $contents .= "Content-Location: $file[filepath]\r\n";
            $contents .= "\r\n";
            $contents .= $file['filecont'];
            $contents .= "\r\n";
        }
        $contents .= "--{$this->boundary}--\r\n";
        return $contents;
    }
    function MakeFile($filename){
        $contents = $this->GetFile();
        $fp = fopen($filename, 'w');
        fwrite($fp, $contents);
        fclose($fp);
    }
    function GetMimeType($filename){
        $pathinfo = pathinfo($filename);
        switch ($pathinfo['extension']) {
            case 'htm': $mimetype = 'text/html'; break;
            case 'html': $mimetype = 'text/html'; break;
            case 'txt': $mimetype = 'text/plain'; break;
            case 'cgi': $mimetype = 'text/plain'; break;
            case 'php': $mimetype = 'text/plain'; break;
            case 'css': $mimetype = 'text/css'; break;
            case 'jpg': $mimetype = 'image/jpeg'; break;
            case 'jpeg': $mimetype = 'image/jpeg'; break;
            case 'jpe': $mimetype = 'image/jpeg'; break;
            case 'gif': $mimetype = 'image/gif'; break;
            case 'png': $mimetype = 'image/png'; break;
            default: $mimetype = 'application/octet-stream'; break;
        }
        return $mimetype;
    }
}
?>

 

 

 

上面討論了通過mht文件,來實(shí)現(xiàn)PHP導(dǎo)出doc格式的。這種方法可以解決一個(gè)難題,就是使導(dǎo)出的doc文件中包含圖片,當(dāng)然,如果您要包含更多的內(nèi)容,比如CSS樣式表,只需要用正則表達(dá)式分析HTML代碼中的link標(biāo)簽,提取css樣式文件的地址,然后讀取并編碼成base64,最后加入到mht文件中就可以了。


以上所述就是本文的全部?jī)?nèi)容了,希望大家能夠喜歡。



如對(duì)本文有疑問,請(qǐng)?zhí)峤坏浇涣髡搲?,廣大熱心網(wǎng)友會(huì)為你解答?。?點(diǎn)擊進(jìn)入論壇

發(fā)表評(píng)論 (983人查看,0條評(píng)論)
請(qǐng)自覺遵守互聯(lián)網(wǎng)相關(guān)的政策法規(guī),嚴(yán)禁發(fā)布色情、暴力、反動(dòng)的言論。
昵稱:
最新評(píng)論
------分隔線----------------------------

其它欄目

· 建站教程
· 365學(xué)習(xí)

業(yè)務(wù)咨詢

· 技術(shù)支持
· 服務(wù)時(shí)間:9:00-18:00
365建站網(wǎng)二維碼

Powered by 365建站網(wǎng) RSS地圖 HTML地圖

copyright © 2013-2024 版權(quán)所有 鄂ICP備17013400號(hào)