2

I have the following code:

protected $_fileSystem;
protected $_directoryList;

public function __construct(
    \Magento\Framework\Filesystem $fileSystem,
    \Magento\Framework\App\Filesystem\DirectoryList $directoryList
) {
    $this->_fileSystem = $fileSystem;
    $this->_directoryList = $directoryList;
    parent::__construct($context);
}

public function execute(){
    $this->writeToCSV();
}

private function writeToCSV(){

    try{
        $media = $this->_fileSystem->getDirectoryWrite($this->_directoryList::MEDIA);
        $media->writeFile('text.txt', 'test');
    }
    catch(Exception $e){
        echo($e->getMessage());
    }

}

However, this doesn't seem to be writing anything to the text file that exists within the same folder as the controller.

1 Answer 1

8

Try Following way,

<?php

protected $filesystem;
protected $directoryList;
protected $csvProcessor;

public function __construct(
    \Magento\Framework\File\Csv $csvProcessor,
    \Magento\Framework\App\Filesystem\DirectoryList $directoryList,
    \Magento\Framework\Filesystem $filesystem
    )
{
    $this->filesystem = $filesystem;  
    $this->directoryList = $directoryList;
    $this->csvProcessor = $csvProcessor;
}

function writeToCsv(){
    $fileDirectoryPath = $this->directoryList->getPath(\Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR);

    if(!is_dir($fileDirectoryPath))
        mkdir($fileDirectoryPath, 0777, true);
    $fileName = 'export.csv';
    $filePath =  $fileDirectoryPath . '/' . $fileName;

    $data = [];
      /* pass data array to write in csv file */
    $data[] = ['orderid' => '100001'];
    $this->csvProcessor
        ->setEnclosure('"')
        ->setDelimiter(',')
        ->saveData($filePath, $data);

    return true;
}

You can check your generated CSV file inside var folder

5
  • I'll give it a whirl. Thanks again Rakesh, always super fast at answering questions. Jan 18, 2019 at 11:32
  • Just a quick question about the directory path. Do I carry on from \Magento\Framework\App\ as though I was in the app folder? So in my case code\company\module? Jan 18, 2019 at 11:38
  • my path is var directory you can set your path Jan 18, 2019 at 11:42
  • @RakeshDonga, How can I collect customer wishlist data and download as a CSV file? Please help me
    – Mohammad
    Dec 29, 2019 at 12:32
  • 1
    @RakeshDonga crystal clear answer.. :) Mar 18, 2020 at 4:00

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.