php 網頁導出word

1、前段時間做的一個項目,用到了網頁導出word、發現導出的是好好的,但是編輯word 的時候,添加圖片,再發給其他人就打不開圖片,今天又從新找了改進了一下。

2、代碼如下

require './word.php';
$date = iconv('UTF-8', 'GB2312', '測試');
$path =  $date . ".doc";
$fileContent = getWordDocument($html,"");
$fp = fopen($path, 'w');
fwrite($fp, $fileContent);
fclose($fp);

 
/**
 * @param $content  html內容
 * @param string $absolutePath         圖片路徑
 * @param bool $isEraseLink
 * @return string
 */
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();
    //這個算法要求src後的屬性值必須使用引號括起來
    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://')
                {
                    //絕對鏈接,不加前綴
                }
                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();
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章