Export CSV file may be a few lines of code, today there is a problem for me for a long time, is the export after the appearance of some HTML code, this should not, the view is empty, controller in the end there is no $this->display (), finally carefully see THINK_ Page_trace such a word, suddenly, is the page tracking log, this default will be output. Finally add a exit to the end of the method, the following is the code:
1.indexcontroller.class.php
<?phpnamespace Home\controller; UseThink\controller;classIndexcontrollerextendsController { Public functionindex () {$hotel= M (' keywords ')->field (' Pagename,page ')Select (); $str= "keyword, name \ 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; UseThink\model;classKeywordsmodelextendsmodel{ Public functionExport_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; }}
The secret is in the last sentence of the IndexController.class.php code here, if you do not write this sentence, the output of Excel has HTML source code, as follows:
thinkphp Exporting a CSV file