将mysql行导出到utf8 csv中

时间:2015-02-16 21:45:26

标签: php mysql csv utf-8

我的数据库目前以utf8格式配置,我正在尝试使用PHP将我的数据库导出到电子表格中。我正在使用此电子表格将数据导入谷歌分析。

虽然每次我尝试导入代码时都会给我这个错误

“文件中的字符无效。仅支持UTF-8编码的字符。”

我正在寻找将mysql数据库导出为csv utf8格式的任何见解或更好的方法。

这是我正在使用的代码。

  function CreateCSV(){
  require_once("/var/www/html/config/DBConn.php");


  $select = "SELECT OrderID,Browser,Cookies,GaCampaign,GaContent,GaMedium,GaReferurl,GaSource,GaTerm,Gclid,IpAddress,GID,JavascriptEnabled,Mobile,OS,Pluginlist,ScreenDimension,Timestamp,UserId FROM OnlineSales ORDER BY OrderID DESC CHARACTER SET utf8";

  $export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

  $fields = mysql_num_fields ( $export );

  for ( $i = 0; $i < $fields; $i++ )
  {
         $header .= mysql_field_name( $export , $i ) . "\t";
  }
  $header= "ga:dimension1   ga:dimension12  ga:dimension17  ga:dimension10  ga:dimension9   ga:dimension7   ga:dimension11  ga:dimension6   ga:dimension8   ga:dimension5   ga:dimension3   ga:dimension4   ga:dimension16  ga:dimension14  ga:dimension13  ga:dimension18  ga:dimension15  ga:dimension19  ga:dimension2";
  while( $row = mysql_fetch_row( $export ) )
  {
      $line = '';
      foreach( $row as $value )
      {                                            
          if ( ( !isset( $value ) ) || ( $value == "" ) )
          {
              $value = "\t";
          }
          else
          {
              $value = str_replace( '"' , '""' , $value );
              $value = '"' . $value . '"' . "\t";
          }
          $line .= $value;
      }
      $data .= trim( $line ) . "\n";
  }
  $data = str_replace( "\r" , "" , $data );

  if ( $data == "" )
  {
      $data = "\n(0) Records Found!\n";                        
  }


  $date = new DateTime();

  header ( 'Content-Type: application/vnd.ms-excel') ;
  header("Content-Disposition: attachment; filename=Export".$date->format('m-d-Y_H-i-s').".csv");
  header("Pragma: no-cache");
  header("Expires: 0");
  print "$header\n$data";

  }


  CreateCSV();

0 个答案:

没有答案