Home  >  Article  >  Backend Development  >  PHP文件下载功能【真实项目】

PHP文件下载功能【真实项目】

WBOY
WBOYOriginal
2016-06-20 12:34:27949browse

    有时候在项目中需要这样一种功能:把数据库里面的数据查询出来后,保存到csv文件里面。然后下载到客户端。开发思路:

  • 先把需要查询的数据从数据库里面查询出来;

  • 把需要查询出来的数据写入到csv文件里面;

  • 3.  保存到客户端(浏览器);

        模拟生产(项目)情况,代码清单如下:
        

    <?php  /**    * 实现下载csv文件    */     //模拟数据     $users = array(       array("username"=>"刘德华","age"=>56,"work"=>"演戏"),       array("username"=>"张学友","age"=>55,"work"=>"唱歌"),     );     $filename = date('Ymd').'.csv';     data2csv($users,$filename);    /**      *@param $data array 从数据库里面查询出来的数据      *@param $download_file_name string 客户端下载后的文件名      */    function data2csv($data,$download_file_name){        header("Content-type:text/csv");  //保存文件的类型        header("Content-Disposition:attachment;filename=".$download_file_name);//保存文件的名字        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');        header('Expires:0');        header('Pragma:public');        ob_start();//开启ob缓存        echo "\xEF\xBB\xBF";        $df   = fopen("php://output",'w');        $head = array_keys(reset($data));        fputcsv($df,$head);//保存第一行        foreach($data as $row){          fputcsv($df,$row);        }        fclose($df);        echo ob_get_clean();    }


    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn