Read input csv file and convert it to arrayHow to Override Core Block, Model and controller in Magento2How to get media directory path in a phtml file in magento 2?How to read data in CSV file and store it to database in Magento 2Parsing a CSV file for custom options scriptForm Click Event in magento 2Date validation on my custom form on frontend magento 2Magento 2 : How can I upload files of dynamically added file input fields in the adminMagento 2 Add new field to Magento_User admin formMagento 2 - Send form data to Controller using AJAX and return Result to PHTMLHow to make file field required pass when submit even it existed valuejquery ajax not working in magento2How to upload and read csv file import into database in magento 2?How to create custom form in Magento 2.2.3
What do you call a situation where you have choices but no good choice?
How can I review my manager, who is fine?
Is it ok for parents to kiss and romance with each other while their 2- to 8-year-old child watches?
Uniform initialization by tuple
How to evaluate the performance of open source solver?
Computer name naming convention for security
Can you create a free-floating MASYU puzzle?
QR codes, do people use them?
Was the 45.9°C temperature in France in June 2019 the highest ever recorded in France?
What exactly is a "murder hobo"?
Why are co-factors 4 and 8 so popular when co-factor is more than one?
Is it possible for a character at any level to cast all 44 Cantrips in one week without Magic Items?
How do ballistic trajectories work in a ring world?
What are the effects of abstaining from eating a certain flavor?
Gory anime with pink haired girl escaping an asylum
Shipped package arrived - didn't order, possible scam?
What purpose does mercury dichloride have in fireworks?
What is the shape of the upper boundary of water hitting a screen?
Is this car delivery via Ebay Motors on Craigslist a scam?
Passwordless authentication - how and when to invalidate a login code
Who goes first? Person disembarking bus or the bicycle?
Intern not wearing safety equipment; how could I have handled this differently?
Does the Wild Magic sorcerer's Tides of Chaos feature grant advantage on all attacks, or just the first one?
What happens if a short can't be covered?
Read input csv file and convert it to array
How to Override Core Block, Model and controller in Magento2How to get media directory path in a phtml file in magento 2?How to read data in CSV file and store it to database in Magento 2Parsing a CSV file for custom options scriptForm Click Event in magento 2Date validation on my custom form on frontend magento 2Magento 2 : How can I upload files of dynamically added file input fields in the adminMagento 2 Add new field to Magento_User admin formMagento 2 - Send form data to Controller using AJAX and return Result to PHTMLHow to make file field required pass when submit even it existed valuejquery ajax not working in magento2How to upload and read csv file import into database in magento 2?How to create custom form in Magento 2.2.3
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
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:
magento2 import csv importexport file-upload
add a comment |
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:
magento2 import csv importexport file-upload
add a comment |
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:
magento2 import csv importexport file-upload
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:
magento2 import csv importexport file-upload
magento2 import csv importexport file-upload
edited May 3 '18 at 3:41
simple guy
asked Nov 30 '17 at 5:05
simple guysimple guy
1,0342 gold badges15 silver badges42 bronze badges
1,0342 gold badges15 silver badges42 bronze badges
add a comment |
add a comment |
3 Answers
3
active
oldest
votes
In your controller file that $postUrl
points to:
protected $csv;
public function __construct(
MagentoFrameworkFileCsv $csv
)
$this->csv = $csv;
//The function name should match your controller path
public function import($file)
if (!isset($file['tmp_name']))
throw new MagentoFrameworkExceptionLocalizedException(__('Invalid file upload attempt.'));
$csvData = $this->csv->getData($file['tmp_name']);
foreach ($csvData as $row => $data)
if ($row > 0)
//Start your work
die();
Note:
- The
$data
is an array object already. It will look likearray(
0 => 'UPS',
1 => 'One Night Service'
......
) - I added
if ($row > 0)
to skip first row as it's the attribute row only. - 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/
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.
– Dinesh Rajput
Jun 28 at 11:44
You can refer to this: magento.stackexchange.com/questions/176490/…
– PY Yick
Jul 2 at 9:29
add a comment |
This it the controller file to save/read imported CSV data:
<?php
namespace VendorNameModuleNameControllerAdminhtmlPincodeImport;
use MagentoFrameworkAppFilesystemDirectoryList;
class Save extends MagentoBackendAppAction
/**
* Authorization level of a basic admin session
*
* @see _isAllowed()
*/
const ADMIN_RESOURCE = 'Vendor_ModuleName::manage_pincodes';
/**
* Image uploader
*
* @var KtplBannerSliderBannerImageUploader
*/
private $csvUploader;
/**
* @var MagentoFrameworkFilesystem
*/
protected $_filesystem;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* CSV Processor
*
* @var MagentoFrameworkFileCsv
*/
protected $csvProcessor;
/**
* @param MagentoBackendAppActionContext $context
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilesystem $filesystem
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilesystem $filesystem,
MagentoFrameworkFileCsv $csvProcessor
)
$this->_filesystem = $filesystem;
$this->_storeManager = $storeManager;
$this->csvProcessor = $csvProcessor;
parent::__construct($context);
/**
* Save action
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @return MagentoFrameworkControllerResultInterface
*/
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>ModelPincode');
$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 KtplBannerSliderBannerImageUploader
*
* @deprecated
*/
private function getCSVUploader()
if ($this->csvUploader === null)
$this->csvUploader = MagentoFrameworkAppObjectManager::getInstance()->get(
'<VendorName><ModuleName>CsvUploader'
);
return $this->csvUploader;
Which part of above code snippet can be used to onlyread
data from csv file?
– Slimshadddyyy
Oct 31 '18 at 20:40
add a comment |
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);
add a comment |
Your Answer
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "479"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f203826%2fread-input-csv-file-and-convert-it-to-array%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
In your controller file that $postUrl
points to:
protected $csv;
public function __construct(
MagentoFrameworkFileCsv $csv
)
$this->csv = $csv;
//The function name should match your controller path
public function import($file)
if (!isset($file['tmp_name']))
throw new MagentoFrameworkExceptionLocalizedException(__('Invalid file upload attempt.'));
$csvData = $this->csv->getData($file['tmp_name']);
foreach ($csvData as $row => $data)
if ($row > 0)
//Start your work
die();
Note:
- The
$data
is an array object already. It will look likearray(
0 => 'UPS',
1 => 'One Night Service'
......
) - I added
if ($row > 0)
to skip first row as it's the attribute row only. - 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/
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.
– Dinesh Rajput
Jun 28 at 11:44
You can refer to this: magento.stackexchange.com/questions/176490/…
– PY Yick
Jul 2 at 9:29
add a comment |
In your controller file that $postUrl
points to:
protected $csv;
public function __construct(
MagentoFrameworkFileCsv $csv
)
$this->csv = $csv;
//The function name should match your controller path
public function import($file)
if (!isset($file['tmp_name']))
throw new MagentoFrameworkExceptionLocalizedException(__('Invalid file upload attempt.'));
$csvData = $this->csv->getData($file['tmp_name']);
foreach ($csvData as $row => $data)
if ($row > 0)
//Start your work
die();
Note:
- The
$data
is an array object already. It will look likearray(
0 => 'UPS',
1 => 'One Night Service'
......
) - I added
if ($row > 0)
to skip first row as it's the attribute row only. - 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/
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.
– Dinesh Rajput
Jun 28 at 11:44
You can refer to this: magento.stackexchange.com/questions/176490/…
– PY Yick
Jul 2 at 9:29
add a comment |
In your controller file that $postUrl
points to:
protected $csv;
public function __construct(
MagentoFrameworkFileCsv $csv
)
$this->csv = $csv;
//The function name should match your controller path
public function import($file)
if (!isset($file['tmp_name']))
throw new MagentoFrameworkExceptionLocalizedException(__('Invalid file upload attempt.'));
$csvData = $this->csv->getData($file['tmp_name']);
foreach ($csvData as $row => $data)
if ($row > 0)
//Start your work
die();
Note:
- The
$data
is an array object already. It will look likearray(
0 => 'UPS',
1 => 'One Night Service'
......
) - I added
if ($row > 0)
to skip first row as it's the attribute row only. - 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/
In your controller file that $postUrl
points to:
protected $csv;
public function __construct(
MagentoFrameworkFileCsv $csv
)
$this->csv = $csv;
//The function name should match your controller path
public function import($file)
if (!isset($file['tmp_name']))
throw new MagentoFrameworkExceptionLocalizedException(__('Invalid file upload attempt.'));
$csvData = $this->csv->getData($file['tmp_name']);
foreach ($csvData as $row => $data)
if ($row > 0)
//Start your work
die();
Note:
- The
$data
is an array object already. It will look likearray(
0 => 'UPS',
1 => 'One Night Service'
......
) - I added
if ($row > 0)
to skip first row as it's the attribute row only. - 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/
answered Nov 30 '17 at 5:28
PY YickPY Yick
1,9038 silver badges21 bronze badges
1,9038 silver badges21 bronze badges
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.
– Dinesh Rajput
Jun 28 at 11:44
You can refer to this: magento.stackexchange.com/questions/176490/…
– PY Yick
Jul 2 at 9:29
add a comment |
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.
– Dinesh Rajput
Jun 28 at 11:44
You can refer to this: magento.stackexchange.com/questions/176490/…
– PY Yick
Jul 2 at 9:29
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.
– Dinesh Rajput
Jun 28 at 11:44
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.
– Dinesh Rajput
Jun 28 at 11:44
You can refer to this: magento.stackexchange.com/questions/176490/…
– PY Yick
Jul 2 at 9:29
You can refer to this: magento.stackexchange.com/questions/176490/…
– PY Yick
Jul 2 at 9:29
add a comment |
This it the controller file to save/read imported CSV data:
<?php
namespace VendorNameModuleNameControllerAdminhtmlPincodeImport;
use MagentoFrameworkAppFilesystemDirectoryList;
class Save extends MagentoBackendAppAction
/**
* Authorization level of a basic admin session
*
* @see _isAllowed()
*/
const ADMIN_RESOURCE = 'Vendor_ModuleName::manage_pincodes';
/**
* Image uploader
*
* @var KtplBannerSliderBannerImageUploader
*/
private $csvUploader;
/**
* @var MagentoFrameworkFilesystem
*/
protected $_filesystem;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* CSV Processor
*
* @var MagentoFrameworkFileCsv
*/
protected $csvProcessor;
/**
* @param MagentoBackendAppActionContext $context
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilesystem $filesystem
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilesystem $filesystem,
MagentoFrameworkFileCsv $csvProcessor
)
$this->_filesystem = $filesystem;
$this->_storeManager = $storeManager;
$this->csvProcessor = $csvProcessor;
parent::__construct($context);
/**
* Save action
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @return MagentoFrameworkControllerResultInterface
*/
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>ModelPincode');
$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 KtplBannerSliderBannerImageUploader
*
* @deprecated
*/
private function getCSVUploader()
if ($this->csvUploader === null)
$this->csvUploader = MagentoFrameworkAppObjectManager::getInstance()->get(
'<VendorName><ModuleName>CsvUploader'
);
return $this->csvUploader;
Which part of above code snippet can be used to onlyread
data from csv file?
– Slimshadddyyy
Oct 31 '18 at 20:40
add a comment |
This it the controller file to save/read imported CSV data:
<?php
namespace VendorNameModuleNameControllerAdminhtmlPincodeImport;
use MagentoFrameworkAppFilesystemDirectoryList;
class Save extends MagentoBackendAppAction
/**
* Authorization level of a basic admin session
*
* @see _isAllowed()
*/
const ADMIN_RESOURCE = 'Vendor_ModuleName::manage_pincodes';
/**
* Image uploader
*
* @var KtplBannerSliderBannerImageUploader
*/
private $csvUploader;
/**
* @var MagentoFrameworkFilesystem
*/
protected $_filesystem;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* CSV Processor
*
* @var MagentoFrameworkFileCsv
*/
protected $csvProcessor;
/**
* @param MagentoBackendAppActionContext $context
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilesystem $filesystem
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilesystem $filesystem,
MagentoFrameworkFileCsv $csvProcessor
)
$this->_filesystem = $filesystem;
$this->_storeManager = $storeManager;
$this->csvProcessor = $csvProcessor;
parent::__construct($context);
/**
* Save action
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @return MagentoFrameworkControllerResultInterface
*/
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>ModelPincode');
$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 KtplBannerSliderBannerImageUploader
*
* @deprecated
*/
private function getCSVUploader()
if ($this->csvUploader === null)
$this->csvUploader = MagentoFrameworkAppObjectManager::getInstance()->get(
'<VendorName><ModuleName>CsvUploader'
);
return $this->csvUploader;
Which part of above code snippet can be used to onlyread
data from csv file?
– Slimshadddyyy
Oct 31 '18 at 20:40
add a comment |
This it the controller file to save/read imported CSV data:
<?php
namespace VendorNameModuleNameControllerAdminhtmlPincodeImport;
use MagentoFrameworkAppFilesystemDirectoryList;
class Save extends MagentoBackendAppAction
/**
* Authorization level of a basic admin session
*
* @see _isAllowed()
*/
const ADMIN_RESOURCE = 'Vendor_ModuleName::manage_pincodes';
/**
* Image uploader
*
* @var KtplBannerSliderBannerImageUploader
*/
private $csvUploader;
/**
* @var MagentoFrameworkFilesystem
*/
protected $_filesystem;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* CSV Processor
*
* @var MagentoFrameworkFileCsv
*/
protected $csvProcessor;
/**
* @param MagentoBackendAppActionContext $context
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilesystem $filesystem
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilesystem $filesystem,
MagentoFrameworkFileCsv $csvProcessor
)
$this->_filesystem = $filesystem;
$this->_storeManager = $storeManager;
$this->csvProcessor = $csvProcessor;
parent::__construct($context);
/**
* Save action
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @return MagentoFrameworkControllerResultInterface
*/
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>ModelPincode');
$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 KtplBannerSliderBannerImageUploader
*
* @deprecated
*/
private function getCSVUploader()
if ($this->csvUploader === null)
$this->csvUploader = MagentoFrameworkAppObjectManager::getInstance()->get(
'<VendorName><ModuleName>CsvUploader'
);
return $this->csvUploader;
This it the controller file to save/read imported CSV data:
<?php
namespace VendorNameModuleNameControllerAdminhtmlPincodeImport;
use MagentoFrameworkAppFilesystemDirectoryList;
class Save extends MagentoBackendAppAction
/**
* Authorization level of a basic admin session
*
* @see _isAllowed()
*/
const ADMIN_RESOURCE = 'Vendor_ModuleName::manage_pincodes';
/**
* Image uploader
*
* @var KtplBannerSliderBannerImageUploader
*/
private $csvUploader;
/**
* @var MagentoFrameworkFilesystem
*/
protected $_filesystem;
/**
* Store manager
*
* @var MagentoStoreModelStoreManagerInterface
*/
protected $_storeManager;
/**
* CSV Processor
*
* @var MagentoFrameworkFileCsv
*/
protected $csvProcessor;
/**
* @param MagentoBackendAppActionContext $context
* @param MagentoStoreModelStoreManagerInterface $storeManager
* @param MagentoFrameworkFilesystem $filesystem
*/
public function __construct(
MagentoBackendAppActionContext $context,
MagentoStoreModelStoreManagerInterface $storeManager,
MagentoFrameworkFilesystem $filesystem,
MagentoFrameworkFileCsv $csvProcessor
)
$this->_filesystem = $filesystem;
$this->_storeManager = $storeManager;
$this->csvProcessor = $csvProcessor;
parent::__construct($context);
/**
* Save action
*
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @return MagentoFrameworkControllerResultInterface
*/
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>ModelPincode');
$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 KtplBannerSliderBannerImageUploader
*
* @deprecated
*/
private function getCSVUploader()
if ($this->csvUploader === null)
$this->csvUploader = MagentoFrameworkAppObjectManager::getInstance()->get(
'<VendorName><ModuleName>CsvUploader'
);
return $this->csvUploader;
answered Nov 30 '17 at 5:28
Ronak ChauhanRonak Chauhan
4,3841 gold badge17 silver badges51 bronze badges
4,3841 gold badge17 silver badges51 bronze badges
Which part of above code snippet can be used to onlyread
data from csv file?
– Slimshadddyyy
Oct 31 '18 at 20:40
add a comment |
Which part of above code snippet can be used to onlyread
data from csv file?
– Slimshadddyyy
Oct 31 '18 at 20:40
Which part of above code snippet can be used to only
read
data from csv file?– Slimshadddyyy
Oct 31 '18 at 20:40
Which part of above code snippet can be used to only
read
data from csv file?– Slimshadddyyy
Oct 31 '18 at 20:40
add a comment |
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);
add a comment |
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);
add a comment |
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);
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);
answered Jun 28 at 12:04
Dinesh RajputDinesh Rajput
777 bronze badges
777 bronze badges
add a comment |
add a comment |
Thanks for contributing an answer to Magento Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f203826%2fread-input-csv-file-and-convert-it-to-array%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown