php 将MySQL导出为CSV(php脚本)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 将MySQL导出为CSV(php脚本)相关的知识,希望对你有一定的参考价值。

<?php
/* vars for export */
// database record to be exported
$db_record = 'XXXXXXXXX';
// optional where query
$where = 'WHERE 1 ORDER BY 1';
// filename for export
$csv_filename = 'db_export_'.$db_record.'_'.date('Y-m-d').'.csv';

// database variables
$hostname = "localhost";
$user = "XXXXXXXXX";
$password = "XXXXXXXXX";
$database = "XXXXXXXXX";

// Database connecten voor alle services
mysql_connect($hostname, $user, $password)
or die('Could not connect: ' . mysql_error());
					
mysql_select_db($database)
or die ('Could not select database ' . mysql_error());

// create empty variable to be filled with export data
$csv_export = '';

// query to get data from database
$query = mysql_query("SELECT * FROM ".$db_record." ".$where);
$field = mysql_num_fields($query);

// create line with field names
for($i = 0; $i < $field; $i++) {
  $csv_export.= mysql_field_name($query,$i).';';
}
// newline (seems to work both on Linux & Windows servers)
$csv_export.= '
';

// loop through database query and fill export variable
while($row = mysql_fetch_array($query)) {
  // create line with field values
  for($i = 0; $i < $field; $i++) {
    $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
  }	
  $csv_export.= '
';	
}

// Export the data and prompt a csv file for download
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=".$csv_filename."");
echo($csv_export);
?>

以上是关于php 将MySQL导出为CSV(php脚本)的主要内容,如果未能解决你的问题,请参考以下文章

忽略空列以将数据导出到 php mysql 中的 csv 文件

PHP 通过PHP将MYSQL导出为EXCEL / CSV

PHP 将MySQL数据导出为CSV

使用 PHP/PDO 将大型 MySQL 表导出为 CSV

PHP 将MySQL查询结果导出为CSV

将mysql的查询结果导出为csv