这是我的代码工作得很好。当我从浏览器调用此文件时,它会以CSV格式下载我的文件。
<?php
/* vars for export */
// database record to be exported
$db_record = 'people';
// optional where query
$where = 'WHERE 1 ORDER BY 1';
// filename for export
$csv_filename = 'exported.csv';
// database variables
$hostname = "localhost";
$user = "root";
$password = "";
$database = "db1";
// 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);
?>
假设生成的文件是这样的:
"name", "age", "country"
"Gulizer", "21", "Kurdistan"
"Pierre", "20", "France"
我想要的是再次回归年龄,并将其放在每行的文本中,如
"name", "age", "country", "text_added"
"Gulizer", "21", "Kurdistan", "The age of Gulizer is 21"
有可能吗?
答案 0 :(得分:0)
我自己找到了解决方案并与您分享
我添加了
echo "text_added;";
之后
for($i = 0; $i < $field; $i++) {$csv_export.= mysql_field_name($query,$i).';';}
$csv_export.= '\n';
并更改了
for($i = 0; $i < $field; $i++) {
$csv_export.= '"'.$row[mysql_field_name($query,$i)].'";';
}
$csv_export.= '
';
}
到
for($i = 0; $i < $field; $i++) { $csv_export.= '"'.$row[mysql_field_name($query,$i)].'";'; }
$csv_export.= '
'.$row['age'].'years old";';
}
最后我得到了这个结果:
text_added;name;age;country
"21 years old"; "Gulizer"; "21"; "Kurdistan"
"20 years old"; "Pierre"; "20"; "France";
正是我想要的。