up vote 1 down vote favorite
share [g+] share [fb]

What I am trying to do is grab a Business Catalyst-generated CSV of my products. But it always includes a whole lot of stuff I don't need.

I have a script that uses fgetcsv(). The code is

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

All this does is display the data I want.

However, what I want to do now is write a new CSV file out of this. Using fwrite() only results in writing just the first entry of the data.

Any ideas?

link|improve this question

75% accept rate
feedback

2 Answers

up vote 0 down vote accepted

Something like this.

<?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);
?>
link|improve this answer
thanks! this does what I want, with me doing str_replace and others before actually writing to $data – jeff Feb 7 at 6:08
feedback

It's very similar to the code you already have:

<?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 has to be a two-dimensional array.

If you want to read your existing file, process its contents and write it to a different file, do it like this:

<?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);
?>
link|improve this answer
this writes all columns, even ones I do not require – jeff Feb 7 at 6:07
You could do something like unset($line_of_text[3]); to remove the forth column. – chiborg Feb 7 at 10:42
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.