8

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

4 Answers 4

19

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 the first row as it's the attribute row only.
  3. You must die() the execution after your job is 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/

3
  • How can I read data from csv that I have uploaded in pub/media folder. I have added the path as $file. But its not detecting file. Its says file doesn't exists. Commented Jun 28, 2019 at 11:44
  • You can refer to this: magento.stackexchange.com/questions/176490/…
    – PY Yick
    Commented Jul 2, 2019 at 9:29
  • It shows me JavaScript may be disabled in your browser. To use this website you must first enable JavaScript in your browser. But my javascript is enabled error and reload the page will you please help me with this @PYYick
    – Prits
    Commented Aug 19, 2020 at 16:20
6

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;
    }
}
1
  • Which part of above code snippet can be used to only read data from csv file? Commented Oct 31, 2018 at 20:40
1

If your .csv file is import by manually then read .csv file data in Array Object

public function __construct(\Magento\Framework\File\Csv $csv)
        {
          $this->csv = $csv;
        }
        /**
         * Execute observer
         *
         * @param \Magento\Framework\Event\Observer $observer
         * @return void
         */
        public function execute(\Magento\Framework\Event\Observer $observer) {
          $csvData = $this->csv->getData($_FILES['import_file']['tmp_name']);
          foreach ($csvData as $row => $data) {
            if ($row > 0){
              echo "<pre>";
              print_r($data);
                }
              }
        die();
       }
-2

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 and acknowledge you have read our privacy policy.

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