我正在尝试将MySQL表格导出为CSV,但也会对其执行格式化。
我的表中有一个名为“meta_value”的列,这是我想要的唯一列。我还想将该列中的数据格式化为csv。
“meta_value”列中的数据如下所示:
["3C9d9SlArYcUsAWszgL68xEEveSzCDNzfJ2hYqPg","Retailer","$1M - $5M","22","10-20","Amazon Canada","InfiPlex","I am a past client","Data Extraction","Browser Search","i like comments","ja@gmail.com"]
导出后,我想删除第一个随机生成的字符串,然后对于其他字符串,我想将它们分离到.csv本身的自己的列中。
我的PHP在下面通过连接到MySQL DB,表和导出CSV来运行。我只是不确定如何进行上面概述的花哨格式化。
谢谢。
<?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);
?>