5

I want to write data in a form to a csv file. I have used the following code:

$data = array();
$data['name'] = $this->getRequest()->getParam('name');
$data['company'] = $this->getRequest()->getParam('company');
$data['email'] = $this->getRequest()->getParam('email');
$data_row[] = $data;

$fileName = "example.csv";

$var_csv = new Varien_File_Csv();

$var_csv->saveData($fileName, $data_row);

But it is not working. Where will be the location of the csv file. Please help.

5
  • whats your $fileName ?
    – Priyank
    Jun 30, 2017 at 9:51
  • $fileName is the csv file to where I want to write the data
    – Vindhuja
    Jun 30, 2017 at 9:52
  • yes give full path of your filepath in and in $filename it will be saved there
    – Priyank
    Jun 30, 2017 at 9:53
  • I want to save this csv file to my root directory. So what do I need to do?
    – Vindhuja
    Jun 30, 2017 at 9:54
  • I have added an answer
    – Priyank
    Jun 30, 2017 at 9:58

2 Answers 2

5

Set Dir path

$path = Mage::getBaseDir('var') . DS . 'export' . DS;
$name = 'yourFileName';
$file = $path . DS . $name . '.csv';

and save it

$var_csv->saveData($file, $data_row);

so it will be saved in <your magento>/var/export/yourFileName.csv

EDIT

If you want to save it in your magento root dir

$path = Mage::getBaseDir();
2
  • Thank you.It worked.One more question ,how can I append the data to the existing csv on submitting the form each time.Please help.
    – Vindhuja
    Jun 30, 2017 at 10:20
  • You can get data from existing file and then append your new data in it and save your csv file.
    – Priyank
    Jun 30, 2017 at 10:30
3

Give this coded a try:

<?php
    error_reporting(E_ALL); ini_set('display_errors', 1);
    $data = array();
    $data['name'] = 'test';
    $data['company'] = 'ghgh';
    $data['email'] = '[email protected]';
    $data_row[] = $data;
    $fileName = "example.csv";
    if(!file_exists($fileName)){
        $file = fopen($fileName, 'w') or die("Can't create file");
    } else {
        $file = fopen($fileName,"w");
    }

    foreach ($data_row as $data)
    {
        fputcsv($file,$data);
    }

    fclose($file);

?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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