2011-03-14 70 views
1

我有以下的PHP腳本,它從兩個CSV文件中讀取,在我將數據放入但是表中我需要它輸出到CSV文件的那一刻...PHP輸出到CSV

<?php 

$products_file = fopen('Products.csv', 'r'); 
$manufacturers_file = fopen('Manufacturers.csv', 'r'); 

$manufacturers = array(); 

while (($manufacturers_line = fgetcsv($manufacturers_file)) !== FALSE) { 

    $manufacturers[$manufacturers_line[0]] = $manufacturers_line [1]; 

    } 

echo '<table><tr><th>SKU</th><th>Make and Model</th><th>Make and Model</th></tr>'; 

while (($products_line = fgetcsv($products_file)) !== FALSE) { 

    echo '<tr><td>'.$products_line[3].'</td><td>'; 

    echo $manufacturers[$products_line[5]]; 

    echo '</td><td>'.$products_line[4].'</td></tr>'; 
} 

echo '</table>'; 

fclose($products_file); 
fclose($manufacturers_file); 

?> 

如何使用fputcsv來做到這一點?

+1

http://php.net/manual/en/function.fputcsv.php是你所需要的。該功能需要一個文件句柄,並將一個數組女巫保存在一行文件中。 – 2011-03-14 15:19:25

回答

2

我建議這樣的:

$outfile = fopen('output.csv', 'w'); 

while (($products_line = fgetcsv($products_file)) !== FALSE 
     && fputcsv(
     array($products_line[3], $manufacturers[$products_line[5]], $products_line[4] 
    ) !== FALSE) { 
    echo '<tr><td>'.$products_line[3].'</td><td>'; 
    echo $manufacturers[$products_line[5]]; 
    echo '</td><td>'.$products_line[4].'</td></tr>'; 
} 

首先,一個新的陣列正在與
array($products_line[3], $manufacturers[$products_line[5]], $products_line[4]創建。
然後這個數組被送到fputcsv()

上面的代碼輸出csv和html。如果您不想要html輸出,請刪除echo

+0

非常感謝,非常完美 – 2011-03-14 15:39:43

3

看起來像你只需要改變它呈現HTML表格將其寫入到這樣一個CSV文件從PHP文件: -

$fp = fopen('newfile.csv', 'w'); 

while (($products_line = fgetcsv($products_file)) !== FALSE) 
{ 
    fputcsv($fp, $products_line); 
} 

fclose($fp); 

希望有所幫助。

Rick。

+0

雖然這將輸出不同於你的html表中的值。 – 2011-03-14 15:27:48

+0

這是真的,因爲它只會輸出整行,但這取決於他想要打印的數據。它可以像創建新陣列一樣輕鬆地進行更改。 – 2011-03-14 15:29:49

+0

Ta非常理查,我最終用upp結束了upp ......很好! – 2011-03-14 16:19:46

3

你也可以這樣來做:

$csv = ''; 

然後在你的while循環填充變量:

$csv .= $products_line[3].','.$manufacturers[$products_line[5]].','.$products_line[4]."\n"; 

然後,一旦外while循環外

申報$ CSV您的循環可以將$ csv寫入文件:

$myFile = 'testFile.csv'; 
$fh = fopen($myFile, 'w') or die('cannot open file'); 
fwrite($fh, $csv); 
fclose($fh); 

完成!

注意圍繞\ n的雙引號。如果您使用單引號,\ n字符將不會有預期的結果。

+0

這很可怕 - 看看你和我的名字和聲譽... – 2011-03-14 15:26:03

+0

@Martin:我知道! – Martin 2011-03-14 15:27:41

+0

+1雙引號\ n - 我不會想到這一點! – 2011-03-14 15:28:52