首先是免责声明,我在这里是一个菜鸟。我试图将我的结果输出到excel文件中,但由于某种原因我似乎无法想象它,所有结果都进入同一列
以下是我用来将其转换为文件的函数:
function createCSVFile($filename,$headings,$data) {
// Set Output Headers
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename={$filename}.csv");
$fp = fopen('php://output', 'w');
$head = array();
foreach ($headings as $heading) {
$head[] = $heading;
}
fputcsv($fp, $head);
$rowData = array();
// Put the data into the csv
foreach ($data as $row) {
foreach ($row as $item) {
$rowData[] = $item;
}
fputcsv($fp, $rowData);
unset($rowData);
}
}
以下是一些示例数据和我传递的结构:
$filename = "Staff-list";
$headings = array("Username","First Name","Last Name","Start Date", "End Date");
$data = getStaffDetails();
返回:
array(6) {
[0]=>
array(5) {
[0]=>
string(12) "James21"
[1]=>
string(3) "James"
[2]=>
string(9) "Michael"
[3]=>
string(10) "2016-06-01"
[4]=>
string(10) "0000-00-00"
}
[1]=>
array(5) {
[0]=>
string(14) "thombommom"
[1]=>
string(5) "Thomas"
[2]=>
string(7) "Bomarius"
[3]=>
string(10) "2016-12-01"
[4]=>
string(10) "0000-00-00"
}
}
根据下面的Marks解决方案,我尝试将PHP函数中的deliminator设置为; ,如下所示:
fputcsv($fp, $head,';');
答案 0 :(得分:1)
我讨厌Windows的原因之一就是每个版本都有所不同,因为开发人员更难。唉....无论如何,你需要做的是覆盖系统设置(&#34;列出分隔符字符&#34;):&#39; sep =;&#39; 。< / p>
你应该传递给 fputcsv 的第一件事是:
$seperator = "sep=;";
fputcsv($fp, $seperator, ';', ' ');
然后让你的数据成为一个数组数组,第一个数组就是你的标题:
$data = array(array("One","Two", "Three"), array('1','2','3'),array('1','2','3'),array('1','2','3'));
只因为你说你是一个菜鸟我会给你整个功能:
function createCSVFile($filename,$data) {
// Set Output Headers
header('Content-Type: text/csv; charset=utf-8');
header("Content-Disposition: attachment; filename={$filename}.csv");
$fp = fopen('php://output', 'w');
// This will override system setting ("list separator character") and Excel will open the file correctly.
$seperator = "sep=;";
fputcsv($fp, $seperator, ';', ' ');
// Get the array initialised.
$rowData = array();
// put the data into the csv
foreach ($data as $row) {
foreach ($row as $item) {
$rowData[] = $item;
}
fputcsv($fp, $rowData);
unset($rowData);
}
}
让我发布!