PHP分号分隔文件生成

时间:2015-03-02 12:10:23

标签: php excel delimiter

我正在使用此代码生成以分号分隔的文件:

for ($i = 0; $i < 3; $i = $i+1)
{   
array_push($dataArray,"$dataCell1","$dataCell2","$dataCell3","$dataCell4","$dataCell5","$dataCell6","$dataCell7","$dataCell8","$dataCell9","$dataCell10","$dataCell11");

$stringData = rtrim(implode(';', $dataArray), ';'); //rtrim will prevent the last cell to be imploded by ';'            

$stringData .= "\r\n";
}   

我想要的是:

enter image description here

(以分号分隔的数据和由newLine分隔的行)

我得到的是: enter image description here (数据以分号分隔,但未添加新行,所有数据都显示在单行中)

请告诉我我做错了什么..

3 个答案:

答案 0 :(得分:1)

你的问题在于你的逻辑。每次迭代时,您都会继续向$ dataArray添加数据,而代码中的以下语句将stingData设置为$ dataArray 仅在最后循环迭代中的内爆值。在那时,$ dataArray包含所有数据值,因为你继续推进它3次迭代。

$stringData = rtrim(...)

你想要做的是:

<?php

//concatenation string
$stringData = '';

for ($i = 0; $i < 3; $i = $i+1)
{ 
    //init the array with every iteration. 
    $dataArray = array();

    //push your values
    array_push($dataArray,"$dataCell1","$dataCell2","$dataCell3","$dataCell4","$dataCell5","$dataCell6","$dataCell7","$dataCell8","$dataCell9","$dataCell10","$dataCell11");

    //concatenate
    $stringData  .= rtrim(implode(';', $dataArray), ';'); 

    //new line
    $stringData .= "\r\n";
} 

//print
echo $stringData . "\n";
?>

答案 1 :(得分:0)

改为使用fputcsv

// indexed array of data
$data = [
    ['col1' => 1, 'col2' => 2, 'col3' => 3],
    ['col1' => 6, 'col2' => 7, 'col3' => 9],
    ['col1' => 5, 'col2' => 8, 'col3' => 15],
]

// add headers for each column in the CSV download
array_unshift($data, array_keys(reset($data)));

$handle = fopen('php://output', 'w');
foreach ($data as $row) {
    fputcsv($handle, $row, ';', '"');
}
fclose($handle);

答案 2 :(得分:0)

为了创建csv文件,fputcsv确实是最好的方法。

首先将数据保存在&#34;阵列数组中#34;。这使得处理数据更容易:

$dataArray = array();

for ($i = 0; $i < 3; $i = $i+1)
    $dataArray[$i] = array($dataCell1,$dataCell2,$dataCell3,$dataCell4,$dataCell5,$dataCell6,$dataCell7,$dataCell8,$dataCell9,$dataCell10,$dataCell11);

接下来,我们需要创建一个临时文件的句柄,同时确保我们有权这样做。然后,我们将使用正确的分隔符将所有数组条目存储在临时文件中。

$handle = fopen('php://temp', 'r+');

foreach($dataArray as $line)
    fputcsv($handle, $line, ';', '"');

rewind($handle);

如果您只想将结果打印到页面,请执行以下代码:

$contents = "";

while(!feof($handle))
    $contents .= fread($handle, 8192);

fclose($handle);

echo $contents;

请注意,在纯HTML中,不会显示换行符。但是,如果您检查结果页面的源代码,则可以看到换行符。

但是如果您还想将值保存在可下载的csv文件中,则需要使用以下代码:

$fileName = "file.csv";
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $fileName . '";');
fpassthru($handle);
fclose($handle);