天天躁日日躁狠狠躁AV麻豆-天天躁人人躁人人躁狂躁-天天澡夜夜澡人人澡-天天影视香色欲综合网-国产成人女人在线视频观看-国产成人女人视频在线观看

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

原理

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

通過(guò)以上的原理介紹,相信大家應(yīng)該對(duì)實(shí)現(xiàn)的過(guò)程有個(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)容,您可以通過(guò)file_put_content將它保存成后綴名為doc的文件
這個(gè)函數(shù)的主要功能其實(shí)就是分析HTML代碼中的所有圖片地址,并且依次下載下來(lái)。獲取到了圖片的內(nèi)容以后,調(diào)用MhtFileMaker類,將圖片添加到mht文件中。具體的添加細(xì)節(jié),封裝在MhtFileMaker類中了。

復(fù)制代碼 代碼如下:
/**
 * 根據(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ì)路徑,那么就需要填寫(xiě)這個(gè)參數(shù),來(lái)讓該函數(shù)自動(dòng)填補(bǔ)成絕對(duì)路徑。這個(gè)參數(shù)最后需要以/結(jié)束
 * @param bool $isEraseLink 是否去掉HTML內(nèi)容中的鏈接
* by www.jb51.NET
 */
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)括起來(lái)
    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();
}


使用方法:

復(fù)制代碼 代碼如下:
$fileContent = getWordDocument($content,"http://www.jb51.NET/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文檔。

復(fù)制代碼 代碼如下:
<?php
/***********************************************************************
Class:        Mht File Maker
Version:      1.2 beta
Author:       Wudi <[email protected]>
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("http://", "/", realpath($dir));
    }

    function SetFirstPage($filename){
        $this->page_first = str_replace("http://", "/", 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.');
        } //www.jb51.NET
        $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;
    }
}
?>

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

php技術(shù)使用PHP導(dǎo)出Word文檔的原理和實(shí)例,轉(zhuǎn)載需保留來(lái)源!

鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。

主站蜘蛛池模板: 李亚男三级 | 一本之道高清www在线观看 | 国产AV果冻传奇麻豆 | 中文字幕午夜乱理片 | 欧美z000z猪| 高中生高潮抽搐喷出白浆视频 | 儿子你得太大了慢点插 | 手机伊在人线香蕉2 | 成人啪啪色婷婷久色社区 | 99re久久精品在线播放 | 涩涩在线视频 | 中文字幕在线视频在线看 | 天天靠天天擦天天摸 | 肉动漫3D卡通无修在线播放 | 久久爱狠狠综合网 | 人成午夜免费视频 | 黄色三级视频在线观看 | 国产AV视频二区在线观看 | 亚洲欧洲日本天天堂在线观看 | 欧美人成人亚洲专区中文字幕 | 久久精品视频在线看99 | 99午夜视频| 无限资源在线观看播放 | 曰本少妇高潮久久久久久 | 国产人妻777人伦精品HD | 国产露脸A片国语露对白 | 在线观看日本污污ww网站 | 草草久久久亚洲AV成人片 | 久久中文字幕乱码免费 | 免费毛片网站在线观看 | 洲精品无码高潮喷水A片 | 免费在线视频成人 | 免费人成视频X8X8国产更快乐 | 国产精品久久久久久免费字体 | 国产69精品久久久久人妻刘玥 | 蜜臀AV精品久久无码99 | 美女的让男人桶爽网站 | 九九热只有精品 | 欧美男男网站免费观看videos | 亚洲 日本 欧美 中文字幕 | 青青草原伊人网 |