作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我的代码,效果非常好。当我从浏览器调用此文件时,它会以 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"
可能吗?
最佳答案
我自己找到了解决方案,分享给大家
我添加了
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";
正是我想要的。
关于php - 如何在从mysql下载的文件的每行末尾添加文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40972857/
我是一名优秀的程序员,十分优秀!