I tried to write a external script for customer import. I get sample customer data from csv file and put them into an array. it was success, and I can see all the data from the array.
Then I tried to add customer programatically. I use Magestore's article as a reference, here.
First I tried using given sample data and it was a success. Customer is added and I can see new customer from magento admin.
But when I tried to use a foreach loop to run same process for my list of customers (I have 10 sample customers in my csv file.), it gives me an exception.
For example, if I use $customer->setEmail('[email protected]');
it will be added and no error. but if I use my array, $customer->setEmail($customerImport[0]);
it shows the exception.
Here is my code, can please someone tell me what's the wrong and how to fix this?
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
$customerImport = getCustomerImport();
function getCustomerImport(){
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$file = 'tesseract/import/customer.csv'; //CSV file path
$arrResult = array();
$headers = false;
$handle = fopen($file, "r");
if (empty($handle) === false) {
while (($data = fgetcsv($handle, 100000, ",")) !== FALSE) {
if (!$headers) {
$headers[] = $data;
} else {
$arrResult[] = $data;
}
}
fclose($handle);
}
try{
$url = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $url->get('\Magento\Store\Model\StoreManagerInterface');
$customerFactory = $objectManager->get('\Magento\Customer\Model\CustomerFactory');
$websiteId = $storeManager->getWebsite()->getWebsiteId();
// $store = $storeManager->getStore(); // Get Store ID
// $storeId = $store->getStoreId();
foreach ($arrResult as $customerImport) {
// Necessary data from csv
$email = (string)$customerImport[0];
$websiteName = $customerImport[1];
$storeName = $customerImport[2];
$confirmationReq = $customerImport[3];
$firstName = $customerImport[4];
$groupId = $customerImport[5];
$lastName = $customerImport[6];
$middleName = $customerImport[7];
$userPrefix = $customerImport[8];
$storeId = $customerImport[9];
$userSuffix = $customerImport[10];
$userUpdatedAt = $customerImport[11];
$websiteId = $customerImport[12];
$userPassword = $customerImport[13];
// Instantiate object (this is the most important part)
$customer = $customerFactory->create();
$customer->setWebsiteId($websiteId);
$customer->setEmail($email);
$customer->setFirstname($firstName);
$customer->setLastname($lastName);
$customer->setPassword($userPassword);
$customer->save();
echo 'Create customer successfully'.$customer->getId();
}
}
catch(Exception $eXp){
echo 'Something failed on customer import '. PHP_EOL;
print_r($eXp);
}
} //end of the function
?>