【发布时间】:2014-01-12 06:52:34
【问题描述】:
这是我从数据库中提取数据到 csv 文件的代码。它工作正常,但现在我把它放在数据有地址的程序中,因此有逗号(,),我在打印它时遇到问题。
看起来是这样的:
Name Address1 Address2 City Email
Name1 123 Mcarthur San Juan City 12 Jones Manila
应该是这样的:
Name Address1 Address2 City Email
Name1 123 Mcarthur, San Juan City 12 Jones, Manila Manila sample@yahoo.com
城市和电子邮件被推送到另一列。我搜索了互联网,但我看到的只是用逗号 (, ) 导入的数据。
另外,php 中的警告和错误消息也会导出到 csv 文件中。我没有那么大的问题,因为一旦我解决了这个问题,我认为不会有任何警告。
那么这是我的代码:
if(isset($_POST['csvextract'])){
$name = "sample";
$file = $name.".csv";
$con = mysql_connect("localhost", "root");
if(!$con){
echo "Error connection";
}
$select_db = mysql_select_db('outbound', $con);
if(!$select_db){
echo "Error to select database";
}
mysql_set_charset("utf8", $con);
header("Content-type: text/csv; charset=UTF-8");
header('Content-disposition: attachment; filename='.basename($file));
$myquery = mysql_query("SELECT * FROM temp");
//While loop to fetch the records
$contents = "Name, Company, Address1, Address2, City, Province, Postal Code, Contact No, Email, Commodity, Type, Weight, Length, Width, Height, Decreased Value, Special Instruction, Shipping Reference, Payment Method, Package No, Tracking No\n";
while($row = mysql_fetch_array($myquery))
{
$contents.=$row['0'].",";
$contents.=$row['1'].",";
$contents.=$row['2'].",";
$contents.=$row['3'].",";
$contents.=$row['4'].",";
$contents.=$row['5'].",";
$contents.=$row['6'].",";
$contents.=$row['7'].",";
$contents.=$row['8'].",";
$contents.=$row['9'].",";
$contents.=$row['10'].",";
$contents.=$row['11'].",";
$contents.=$row['12'].",";
$contents.=$row['13'].",";
$contents.=$row['14'].",";
$contents.=$row['15'].",";
$contents.=$row['16'].",";
$contents.=$row['17'].",";
$contents.=$row['18'].",";
$contents.=$row['19'].",";
$contents.=$row['20'].",";
$contents.=$row['21']."\n";
}
$contents_final = chr(255).chr(254).mb_convert_encoding($contents, "UTF-16LE","UTF-8");
print $contents_final;
}
【问题讨论】:
-
你为什么不使用
fputcsv()?如果它包含分隔符,它将在值周围加上引号。 -
我尝试使用 fputcsv 但我得到的只是一个空白页。
-
您是否使用
php://stdout作为输出文件?还是常量STDOUT? -
没有。这是我用来导出它的唯一代码。
-
好吧,如果你想将 CSV 发送到浏览器,这就是你必须做的。如果您正在写入文件,那么您当然会得到一个空白页。
标签: php mysql csv export comma