我正在尝试将我的PHP代码输出到可下载的CSV文件中,到目前为止,我能够执行此操作,但此时输出不会将字段数据放入单独的列中。相反,它将所有内容放入一列,除此之外,它还在其相邻列中显示邮政编码。有谁知道这是为什么?
<?php
header("Content-type: text/csv");
header("Cache-Control: no-store, no-cache");
header('Content-Disposition: attachment; filename="filename.csv"');
$outstream = fopen("php://output",'w');
if ($db_found) {
// Select all fields from bodyshops_master_network table
$SQL = "SELECT * FROM bodyshops_master_network";
$result = mysql_query($SQL);
while ( $db_field = mysql_fetch_assoc($result) ) {
// Splits the arrays
$row = explode(",", $db_field['postcodes_covered']);
$dealer_code = $db_field['dealer_code'];
$dealer_name = $db_field['dealer_name'];
$bodyshop_id = $db_field['bodyshop_id'];
$bodyshop_name = $db_field['bodyshop_name'];
$address1 = $db_field['address1'];
$address2 = $db_field['address2'];
$address3 = $db_field['address3'];
$address4= $db_field['address4'];
$address5 = $db_field['address5'];
$postcode = $db_field['postcode'];
$bo_tel = $db_field['BO_tel'];
$bo_email = $db_field['BO_email'];
$bc_name = $db_field['BC_name'];
$equity_contract = $db_field['equity_contract'];
echo "<pre>";
foreach ($row as $value) {
echo $dealer_code . " ";
echo $dealer_name . " ";
echo $bodyshop_id . " ";
echo $bodyshop_name . " ";
echo $address1 . " ";
echo $address2 . " ";
echo $address3 . " ";
echo $address4 . " ";
echo $address5 . " ";
echo $postcode . " ";
echo $bo_tel . " ";
echo $bo_email . " ";
echo $bc_name . " ";
echo $equity_contract . " ";
echo $value. "<BR>";
fputcsv($outstream, $row, ',', '"');
}
echo "</pre>";
}
mysql_close($db_handle);
} else {
print "Database NOT Found ";
mysql_close($db_handle);
fclose($outstream);
}
?>
答案 0 :(得分:1)
首先,使用echo
以正常方式输出内容。足够公平!
其次,使用文件处理程序指向fputcsv
的{{1}}输出内容。还够公平!
但是你不应该同时做这两件事并期望它能够无缝地工作。您需要CSV文件,因此最好的方法是使用php://output
输出所有数据。目前,您的一些数据被封装为CSV文件,而其中一些则不是。这导致您不想要的输出。
我想你想要这样的东西:
fputcsv
foreach ($row as $value) {
$output = array(
$dealer_code,
$dealer_name,
$bodyshop_id,
$bodyshop_name,
$address1,
$address2,
$address3,
$address4,
$address5,
$postcode,
$bo_tel,
$bo_email,
$bc_name.
$equity_contract,
$value
);
fputcsv($outstream, $output, ',', '"');
}
期望数据是一个数组,这就是我们提供的数据。单独的数组字段将是CSV输出中的单独列。我们没有fputcsv
任何数据:我们将其存储在数组中,然后将其提供给echo
。
您犯的第二个错误是将fputcsv
而不是$row
发送给$value
。这意味着您要发送从数据库行收到的所有邮政编码。
最后,您不需要fputcsv
。
另外,确实应该有更好的数据库结构。如果你有一个邮政编码表和一个单独的 bodyshops表和一个链接它们的外键,那么检索数据的代码将会更加简单,将来会搜索和更新它。