想你了的他他 发表于 2015-8-30 11:53:11

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' );
    }
页: [1]
查看完整版本: php 将数据下载为csv文件