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(); }