使用此代码,我可以从mysql数据库获取数据并将其保存为.csv格式。
<?php
$filename = 'text.csv';
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);
$host="";
$uname="";
$pass="";
$database = "";
$connection=mysql_connect($host,$uname,$pass);
echo mysql_error();
//or die("Database Connection Failed");
$selectdb=mysql_select_db($database) or die("Database could not be selected");
$result=mysql_select_db($database)
or die("database cannot be selected <br>");
$sqlagentdetails = "select * from users WHERE company_name != ''";
$rowresult = mysql_query($sqlagentdetails);
echo "Coloumn 1";
echo "Column 2";
echo "\n";
while($row = mysql_fetch_array($rowresult, MYSQL_ASSOC))
{
$myQuery = mysql_query( /* query are goes to here...*/ );
while($row = mysql_fetch_array($myQuery)){
$postcode = "{$row['postcode']}";
$paddress = "{$row['paddress']}";
echo "$emailAgent $paddress" . "\n";
}
}
?>
它已成功将数据保存为.csv格式,但问题是当我查看.csv文件时。它显示的结果如下:
--------------------------
Column 1 Column 2
-------------------------
result 1 result 2
result 1 result 2
result 1 result 2
result 1 result 2
但TI应该显示为(IT必须显示每个列的每个值,而不是每个列的值)
--------------------------
Column 1 Column 2
-------------------------
result 1 result 2
result 1 result 2
result 1 result 2
result 1 result 2
如何将此.csv文件结果逐列保存?
答案 0 :(得分:0)
如果您希望列之间有 TAB ,请将其放在echo
语句中:
echo "Column 1\tColumn 2\n";
while($row = mysql_fetch_array($rowresult, MYSQL_ASSOC))
{
$myQuery = mysql_query( /* query are goes to here...*/ );
while($row = mysql_fetch_array($myQuery)){
$postcode = $row['postcode'];
$paddress = $row['paddress'];
echo "$postcode\t$paddress" . "\n";
}
当这是整个字符串时,也没有必要用"{...}"
包装数组引用。