2015-03-02 75 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);