php 将数据下载为csv文件


    /**
     * 下载 CSV 数据为CSV文件
     */
    public function downloadCsvData( $csv_data = array())
    {
        /****************************************************************************************************************************
         * 新建csv数据
        /****************************************************************************************************************************/
        $csv_string = null;
        $csv_row    = array();
        foreach( $csv_data as $key => $csv_item )
        {
            if( $key === 0 )
            {
                $csv_row[]    = implode( "\t" , $csv_item );
                continue;
            }
            $current    = array();
            foreach( $csv_item AS $item )
            {

          /****************************************************************************************************************************
           *很关键。 默认csv文件字符串需要 ‘ " ’ 环绕,否则导入导出操作时可能发生异常。
          /****************************************************************************************************************************/
                $current[] = is_numeric( $item ) ? $item : '"' . str_replace( '"', '""', $item ) . '"';
            }
            $csv_row[]    = implode( "\t" , $current );
        }
        $csv_string = implode( "\r\n", $csv_row );
        /****************************************************************************************************************************
         * 输出
        /****************************************************************************************************************************/
         header("Content-type:text/csv");
         header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=data_package.".date('Y-m-d').".csv");
        header('Expires:0');
        header('Pragma:public');
        echo "\xFF\xFE".mb_convert_encoding( $csv_string, 'UCS-2LE', 'UTF-8' );
    }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM