2012-02-06 65 views
1

我試圖做的是抓取Business Catalyst生成的我的產品CSV文件。但它總是包含我不需要的大量東西。使用php寫入多個嵌套數組到文件使用php

我有一個使用fgetcsv()的腳本。代碼是

<?php 
$file_handle = fopen("ProductExport2.csv", "r"); 
    while (!feof($file_handle)) { 
$line_of_text = fgetcsv($file_handle, 1000000); 
      $tableDisplay = "<tr><td>" . $line_of_text[0] . "</td><td>" . $line_of_text[1] . "</td><td>" . $line_of_text[2] . "</td><td>" . $line_of_text[4] . "</td><td>" . $line_of_text[6] . "</td><td>" . $line_of_text[49] . "</td></tr>"; 
      echo $tableDisplay; 
    } 
fclose($file_handle); 
?> 

所有這些都是顯示我想要的數據。

但是,我現在要做的是寫一個新的CSV文件。使用fwrite()只會導致只寫入數據的第一個條目。

任何想法?

回答

0

就是這樣。

<?php 
    $file_handle = fopen("ProductExport2.csv", "r"); 
    $data = ''; 
    while (!feof($file_handle)) { 
     $line_of_text = fgetcsv($file_handle, 1000000); 
     $data .= $line_of_text[0] . "," . $line_of_text[1] . "," . $line_of_text[2] . "," . $line_of_text[4] . "," . $line_of_text[6] . "," . $line_of_text[49] . "\n\r"; 
    } 
    fclose($file_handle); 

    $new_file_handle = fopen("ProductExport2_reduced.csv", "w"); 
    fwrite($new_file_handle, $data); 
?> 
+0

的感謝!這是做我想做的事情,與我做str_replace和其他人之前,實際寫入$ data – jeffimperial 2012-02-07 06:08:29

0

這是非常相似,你已經擁有的代碼:

<?php 
$file_handle = fopen("ProductExport2.csv", "w"); 
    // Iterate through the data entries 
    foreach($my_data as $entry) { 
     // Write the "columns" of each entry as a comma-separated string to the file 
     fputcsv($file_handle, $entry); 
    } 
fclose($file_handle); 

$my_data必須是一個二維數組。

如果你想讀你現有的文件,進程的內容,並將其寫入到不同的文件,像這樣做:

<?php 
$file_handle = fopen("ProductExport2.csv", "r"); 
$file_handle_output = fopen("ProductExport2_new.csv", "w"); 
while (!feof($file_handle)) { 
    $line_of_text = fgetcsv($file_handle, 1000000); 
    // Change $line_of_text elements here 
    // for example $line_of_text[1] += 100; 
    // ... 
    fputcsv($file_handle_output, $line_of_text);  
} 
fclose($file_handle); 
fclose($file_handle_output); 
?> 
+0

這寫所有列,即使我不需要 – jeffimperial 2012-02-07 06:07:33

+0

你可以做一些像'unset($ line_of_text [3]);'刪除第四列。 – chiborg 2012-02-07 10:42:44