magento 2 从 ftp 读取 csv 返回一个字符串而不是数组

问题描述 投票:0回答:3

我正在使用 Magento 2,我需要通过 ftp 连接读取文件。我可以登录 ftp,但无法读取 csv 文件。到目前为止我做了什么(我删除了所有不必要的部分):

use Magento\Framework\File\Csv;
use Magento\Framework\Filesystem\Io\Ftp;

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)
    }
}

如何将 csv 作为数组读取,因为

$this->_csvprocessor->getData()
会返回,但从远程文件而不是本地文件?

php ftp magento2
3个回答
0
投票

您需要解析 csv 字符串。尝试使用函数“fgetcsv”。请参阅 http://php.net/manual/en/function.fgetcsv.php


0
投票

在代码下面,您可以使用数组读取CSV文件

    use Magento\Framework\App\Bootstrap;
    include('app/bootstrap.php');
    $bootstrap = Bootstrap::create(BP, $_SERVER);
    $objectManager = $bootstrap->getObjectManager();
    $objectManager1 = Magento\Framework\App\ObjectManager::getInstance();
    $directoryList = $objectManager1->get('\Magento\Framework\App\Filesystem\DirectoryList');
    $path = $directoryList->getPath('media');
    $state = $objectManager->get('Magento\Framework\App\State');
    $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....

}

希望这能帮助您享受...


0
投票

您可以将服务器文件转储到本地。

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

其中 $destinationFilePath 是本地文件路径。 然后使用该本地文件。

© www.soinside.com 2019 - 2024. All rights reserved.