6

I have an input file form in phtml to import data from csv file type like this:

<div class="import-shipping">
  <div class="header">
    <h4>CSV File:</h4>
  </div>
  <form class="import-shipping-form" action="<?= $postUrl ?>" method="POST" enctype="multipart/form-data">
    <?php echo $block->getBlockHtml('formkey'); ?>
    <input type="file" required class="required-entry" name="csv" />
    <button type="submit">Import</button>
  </form>
</div>

How can i read the csv file and turn it into an array, and validate the file input file type is csv in my controller?

for example my csv file look like this:

csv file example

8

In your controller file that $postUrl points to:

protected $csv;

public function __construct(
    \Magento\Framework\File\Csv $csv
)
{
     $this->csv = $csv;
}

//The function name should match your controller path
public function import($file)
{
     if (!isset($file['tmp_name'])) 
        throw new \Magento\Framework\Exception\LocalizedException(__('Invalid file upload attempt.'));

     $csvData = $this->csv->getData($file['tmp_name']);

     foreach ($csvData as $row => $data) {
         if ($row > 0){
             //Start your work
         }
     }
     die();
}

Note:

  1. The $data is an array object already. It will look like array( 0 => 'UPS', 1 => 'One Night Service' ...... )
  2. I added if ($row > 0) to skip first row as it's the attribute row only.
  3. You must die() the execution after your job done. I assume your controller is custom made. If you want to override the core controller, please see here.

Ref: https://www.magestore.com/magento-2-tutorial/how-to-readwrite-csv-file-from-magento/

2

This it the controller file to save/read imported CSV data:

<?php

namespace VendorName\ModuleName\Controller\Adminhtml\Pincode\Import;

use Magento\Framework\App\Filesystem\DirectoryList;

class Save extends \Magento\Backend\App\Action
{
    /**
     * Authorization level of a basic admin session
     *
     * @see _isAllowed()
     */
    const ADMIN_RESOURCE = 'Vendor_ModuleName::manage_pincodes';

    /**
     * Image uploader
     *
     * @var \Ktpl\BannerSlider\BannerImageUploader
     */
    private $csvUploader;

    /**
     * @var \Magento\Framework\Filesystem
     */
    protected $_filesystem;

    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * CSV Processor
     *
     * @var \Magento\Framework\File\Csv
     */
    protected $csvProcessor;

    /**
     * @param Magento\Backend\App\Action\Context $context
     * @param Magento\Store\Model\StoreManagerInterface $storeManager
     * @param Magento\Framework\Filesystem $filesystem
     */
    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Filesystem $filesystem,
        \Magento\Framework\File\Csv $csvProcessor
    ) {
        $this->_filesystem = $filesystem;
        $this->_storeManager = $storeManager;
        $this->csvProcessor = $csvProcessor;
        parent::__construct($context);
    }

    /**
     * Save action
     *
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     * @return \Magento\Framework\Controller\ResultInterface
     */
    public function execute()
    {
        $data = $this->getRequest()->getPostValue();

        $resultRedirect = $this->resultRedirectFactory->create();

        try {
            if(isset($data['file_upload']['0'])) {
                $data['file_upload'] = $data['file_upload']['0']['name'];
            }
            else {
                $data['file_upload'] = null;
            }

            if(isset($data['file_upload']) && !is_null($data['file_upload']))
            {
                $this->getCSVUploader()->moveFileFromTmp($data['file_upload']);

                $mediaPath = $this->_filesystem->getDirectoryRead(DirectoryList::MEDIA)->getAbsolutePath()
                     . '<moduleroute_code>/pincode/' . $data['file_upload'];

                $importProductRawData = $this->csvProcessor->getData($mediaPath);

                $count = 0;

                foreach ($importProductRawData as $rowIndex => $dataRow) 
                {
                    if($rowIndex > 0) 
                    {
                        $model = $this->_objectManager->create('<Vendor>\<ModuleName>\Model\Pincode');

                        $model->loadByPincode($dataRow[0])
                            ->setData('pincode', $dataRow[0])
                            ->setData('is_cod_available', $dataRow[1])
                            ->setData('delivery_time', $dataRow[2])
                            ->setData('delivery_message', $dataRow[3])
                            ->setData('is_active', $dataRow[4])
                            ->save();

                        $count++;
                    }
                }

                $this->messageManager->addSuccess(__('Total %1 pincodes added / updated successfully.', $count));
            }
            else
                $this->messageManager->addError(__('CSV file not uploaded properly, please try again!'));
        } catch (\Exception $e) {
            $this->messageManager->addError($e->getMessage());
        }

        return $resultRedirect->setPath('*/pincode/index');
    }

    /**
     * Get image uploader
     *
     * @return \Ktpl\BannerSlider\BannerImageUploader
     *
     * @deprecated
     */
    private function getCSVUploader()
    {
        if ($this->csvUploader === null) {
            $this->csvUploader = \Magento\Framework\App\ObjectManager::getInstance()->get(
                '<VendorName>\<ModuleName>\CsvUploader'
            );
        }
        return $this->csvUploader;
    }
}
  • Which part of above code snippet can be used to only read data from csv file? – Slimshadddyyy Oct 31 '18 at 20:40
0

If your .csv file is in pub media folder or other folder.

You can read csv file simply by: you just have to give your .csv path like pub/media, root of magento etc in $file.

$file = 'csv/products.csv';
$handle = fopen($file, "r");
if (empty($handle) === false) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        var_dump($data);
    }
    fclose($handle);
  }

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.