1

我想要做的是获取我的产品的 Business Catalyst 生成的 CSV。但它总是包含很多我不需要的东西。

我有一个使用 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() 只会导致只写入数据的第一个条目。

有任何想法吗?

4

2 回答 2

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);
?>
于 2012-02-06T10:35:13.873 回答
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);
?>
于 2012-02-06T10:35:47.807 回答