gpt4 book ai didi

php - 如何在从mysql下载的文件的每行末尾添加文本?

转载 作者:行者123 更新时间:2023-11-29 19:46:00 25 4
gpt4 key购买 nike

这是我的代码,效果非常好。当我从浏览器调用此文件时,它会以 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com