skip to Main Content

I’m working with Magento 2, I need to read a file through ftp connection. I can login to ftp but I cannot read the csv file. What I did so far (I cut all the unnecessary parts):

use MagentoFrameworkFileCsv;
use MagentoFrameworkFilesystemIoFtp;

class MyClass {
    protected $_csvprocessor;
    protected $_ftp;
    public function __construct(Csv $csvprocessor, Ftp $ftp) {
        $this->_csvprocessor = $csvprocessor;
        $this->_ftp = $ftp;
    }
    public function getCsv() {
        $conn = $this->_ftp->open($params); // this works, I can successfully login to ftp
        $filecsv = $this->_ftp->read($remotepathtofile); // this gets me the file but it is a string, not an array with the csv data
        $this->_csvprocessor->getData($remotepathtofile); // this doesn't work with remote file, only with local path (eg: magentoroot/var/import/file.csv)
    }
}

How can I read the csv as an array, as $this->_csvprocessor->getData() would return, but from remote file instead of local?

3

Answers


  1. You need to parse the csv string. Try using the function “fgetcsv”. See http://php.net/manual/en/function.fgetcsv.php.

    Login or Signup to reply.
  2. Below the code, you can use to read CSV file an array

        use MagentoFrameworkAppBootstrap;
        include('app/bootstrap.php');
        $bootstrap = Bootstrap::create(BP, $_SERVER);
        $objectManager = $bootstrap->getObjectManager();
        $objectManager1 = MagentoFrameworkAppObjectManager::getInstance();
        $directoryList = $objectManager1->get('MagentoFrameworkAppFilesystemDirectoryList');
        $path = $directoryList->getPath('media');
        $state = $objectManager->get('MagentoFrameworkAppState');
        $state->setAreaCode('frontend');
        $myarray = glob("Book1.csv"); 
        usort($myarray, create_function('$a,$b', 'return filemtime($a) - filemtime($b);'));
        if(count($myarray)){
            /*This will create an array of associative arrays with the first row column headers as the keys.*/
            $csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
            array_walk($csv_map, function(&$a) use ($csv_map) {
              $a = array_combine($csv_map[0], $a);
            });
            array_shift($csv_map); # remove column header
            /*End*/
    
            $message = '';
            $count   = 1;
            foreach($csv_map as $data){ 
    
    your code....
    
    }
    

    Hope this will help you enjoy…

    Login or Signup to reply.
  3. You can dump the server file to your local.

       $filecsv = $this->_ftp->read($remotepathtofile, $destinationFilePath);
    

    where $destinationFilePath is local file path.
    Then use that local file.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search