用php语句输出时间格式,总结使用php语言导出word文档

对于新手来说, 听到说导出word文档的功能, 可能就会把这个功能想复杂,其实导出word并不是很难,因为我们用到的很多东西别人已经给我们封装好了,我们只需要进行简单的调用就可以实现导出word这个功能。

有需要的小伙伴可以参考一下哦。

下面给大家分享一下代码吧!

#提示:代码都是基于ThinkPHP5的  但流程都差不多。

注意的是我们必须正确引入wordmake类。

/**

* 1,查找需要导出的数据内容

* 2,调用wordmake生成word内容

* 3,写入文件

* 4,通过浏览器下载

*/

public function index(){

$data = db('user')

->field('user_id,account_number,phone,username,sign,content,head_img')

->limit(2)

->select(); //从数据库查询数据

$this->assign("info",$data); //把获取的数据传递的模板,替换模板里面的变量

$content = $this->fetch('index'); //获取模板内容信息word是模板的名称

$fileContent = $this->WordMake($content); //生成word内容

//创建文件

$date = date('Y-m-d-His', time());

$filename = $date.'.doc'; //获得文件名

$my_file = 'public/upload/word/'.$filename; //保存路径

$fp = fopen( $my_file, 'w') or die('Cannot open file: '.$my_file);//创建并打开生成的文档 打开失败则截断

fwrite($fp, $fileContent); //写入包 保存文件

//通过浏览器下载

Header( "Content-type: application/octet-stream ");

Header( "Accept-Ranges: bytes ");

Header( "Content-Disposition: attachment; filename= $filename");

fclose($fp); //关闭资源

}

下面这个方法无需改动即可使用:

/**

* 根据HTML代码获取word文档内容

* @param $content HTML内容

*

* 网页的绝对路径。如果HTML内容里的图片路径为相对路径,

* 那么就需要填写这个参数,来让该函数自动填补成绝对路径。这个参数最后需要以/结束

* @param string $absolutePath

* @param bool $isEraseLink 是否去掉HTML内容中的链接

* @return string

*/

private function WordMake( $content , $absolutePath = "" , $isEraseLink = true )

{

$mht = new Wordmaker();

if ($isEraseLink){

$content = preg_replace('/(\s*.*?\s*)/i' , '$1' , $content); //去掉链接

$content = preg_replace('//i' , '$1' , $content); //去掉链接

$content = preg_replace('/

}

$images = array();

$files = array();

$matches = array();

//这个算法要求src后的属性值必须使用引号括起来

if ( preg_match_all('//i',$content ,$matches ) ){

$arrPath = $matches[1];

for ( $i=0;$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

{

$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!
";

}

}

return $mht->GetFile();

}

需要的类文件下载地址:Wordmaker

点个赞也不建议哦!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值