這是我從數據庫中提取數據到csv文件的代碼。它工作正常,但現在我把它放在我的程序中,數據有地址,因此有逗號(,),我在打印時遇到問題。用','從數據庫中提取數據到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 [email protected]
城市和電子郵件都推到另一列。我搜索了互聯網,但我看到的所有數據都帶有逗號(,)。
另外,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()'?如果它包含分隔符,它會在值附近加上引號。 – Barmar
我嘗試使用fputcsv,但我得到的只是一個空白頁面。 – nicole101
你使用'php:// stdout'作爲輸出文件嗎?或者不斷的'STDOUT'? – Barmar