2015-03-02 76 views
2

我使用这个代码来生成一个分号分隔的文件:PHP分号分隔的文件生成

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 (数据用分号隔开,但不会添加新的生产线,所有的数据出现在SNGLE线)

请告诉我,我做错了..

+0

使用''
,而不是'\ r \ N'。此外,您可以使用'$ i ++'而不是'$ i = $ i + 1'。 – Albzi 2015-03-02 12:12:28

+0

使用[fputcsv()](http://php.net/manual/en/function.fputcsv.php)代替这个破碎的自制软件;并使用正确的标题,所以输出被视为CSV而不是HTML标记 – 2015-03-02 12:14:15

回答

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"; 
?> 
+0

该怎么能跳过这样的质量步骤在这里:)谢谢你! – user3202144 2015-03-03 04:23:46

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); 
0

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

首先将数据保存在“数组数组”中。这使得处理数据更容易:

$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);