标签:style blog http color io os ar 文件 2014
导出csv文件可能就那几行代码,今天有个问题困扰我好久,就是导出之后出现一些html代码,这个不应该,view里面是空的,controller中最后也没有$this->display(),最后细心看到think_page_trace这样的字样,恍然大悟,是页面的跟踪日志,这个默认是会输出来的。最后在方法后面加了一个exit结束就好了,下面是代码:
1.IndexController.class.php
<?php namespace Home\Controller; use Think\Controller; class IndexController extends Controller { public function index(){ $hotel = M(‘keywords‘)->field(‘PageName,Page‘)->select(); $str = "关键字,名称\n"; $str = iconv(‘utf-8‘,‘gb2312‘,$str); $result = mysql_query("select PageName,Page from hotel_keywords"); while($row=mysql_fetch_array($result)){ $PageName = iconv(‘utf-8‘,‘gb2312‘,$row[‘PageName‘]); $Page = iconv(‘utf-8‘,‘gb2312‘,$row[‘Page‘]); $str .= $PageName.",".$Page."\n"; } $fileName = date(‘Ymd‘).‘.csv‘; $model = D(‘Keywords‘); $model->export_csv($fileName,$str); exit; } }
2.KeywordsModel.class.php
<?php namespace Home\Model; use Think\Model; class KeywordsModel extends Model{ public function export_csv($filename, $data){ header("Content-type:text/csv"); header("Content-Disposition:attachment;filename=".$filename); header(‘Cache-Control:must-revalidate,post-check=0,pre-check=0‘); header(‘Expires:0‘); header(‘Pragma:public‘); echo $data; } }
奥妙就在IndexController.class.php代码最后一句的exit这里,如果不写这句,输出的excel里面有html源码,截图如下:
标签:style blog http color io os ar 文件 2014
原文地址:http://www.cnblogs.com/tylerdonet/p/3987200.html