thinkphp Exporting a CSV file

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.