1

I am using Varien_File_Csv to save CSV data.

$csv = new Varien_File_Csv();
$csv->saveData($fileName, $data);

This approach always rewrites the CSV output file. Is there any way to use append method to output file instead of rewrite?

  • What do you mean by "rewrite the CSV output file" ? What is the problem exactly ? – Raphael at Digital Pianism Mar 23 '16 at 11:52
  • I reckon there's no need to extend the class, it already provides a high number of public methods to specify the CSV parameters. – Raphael at Digital Pianism Mar 23 '16 at 11:55
  • To use append mode instead of rewrite to output file. – vladPavlov Mar 23 '16 at 11:56
  • Unfortunately, there are no public methods which should be used for this purpose. – vladPavlov Mar 23 '16 at 11:59
  • 2
    I found Varien_File_Csv to not be useful at all in most cases and would recommend to use SplFileObject (or a custom solution) instead. I explained it in detail at schmengler-se.de/en/2015/03/csv-processing-with-magento – Fabian Schmengler Mar 23 '16 at 12:00
1

I found the solution, by extending the class Varien_File_Csv, and rewriting the method saveData to change:

$fh = fopen($file, 'w');

to

$fh = fopen($file, 'a');
1

Instead of rewriting the class you could also have done:

$csv = new Varien_File_Csv();
// Get original data
$orgData = $csv->getData($fileName);
$csv->saveData($fileName,$orgData);
$csv->saveData($fileName,$data);
0

Extending the Varien_File_Csv will do the trick. I opened mine to allow all fopen file modes

class Custom_File_Csv extends Varien_File_Csv
{
    /**
     * Overrides saveData function with file options
     *
     * @param [type] $file
     * @param [type] $data
     * @param string $fileoption
     * @return void
     */
    public function saveData($file, $data, $fileoption = 'w')
    {
        $fh = fopen($file, $fileoption);
        foreach ($data as $dataRow) {
            $this->fputcsv($fh, $dataRow, $this->_delimiter, $this->_enclosure);
        }
        fclose($fh);
        return $this;
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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