0

I want to import 20.000 coupon codes on my website, and for this reason, I created the following script:

<?php
use Magento\Framework\App\Bootstrap; 

/**
 * If your external file is in root folder
 */
require __DIR__ . '/app/bootstrap.php';

// Import CSV from ViArt format:
$handle = fopen('coupons.csv', 'r');
$cols   = array_flip(fgetcsv($handle));

while($data = fgetcsv($handle))
{

    if($data[$cols['is_active']] == 1)
    {
        echo 'Importing coupon with code: '.$data[$cols['coupon_code']].'<br />';
        createCoupon(
            $data[$cols['coupon_code']],
            $data[$cols['description']],
            'by_fixed',
            $data[$cols['discount_amount']]
        );
    } else {
        echo 'Not imported (not active): '.$data[$cols['coupon_code']].'<br />';
    }
}


/**
* CREATE COUPONS
*/
function createCoupon($code, $description, $type, $amount, $options = array())
{

$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
//$state->setAreaCode('frontend');
$state->setAreaCode('adminhtml');  

$coupon['name'] = '10% Footers';
$coupon['desc'] = 'Discount for vip signup coupon.';
$coupon['start'] = date('Y-m-d');
$coupon['end'] = '';
$coupon['max_redemptions'] = 1000;
$coupon['discount_type'] ='by_percent';
$coupon['discount_amount'] = 15;
$coupon['flag_is_free_shipping'] = 'no';
$coupon['redemptions'] = 1;
$coupon['code'] ='NL01-1234'; //this code will normally be autogenetated but i am hard coding for testing purposes

$shoppingCartPriceRule = $obj->create('Magento\SalesRule\Model\Rule');
$shoppingCartPriceRule->setName($coupon['name'])
        ->setDescription($description)
        ->setFromDate($coupon['start'])
        ->setToDate($coupon['end'])
        ->setUsesPerCustomer($coupon['max_redemptions'])
        ->setCustomerGroupIds(array('0','1','2','3',))
        ->setIsActive(1)
        ->setSimpleAction($coupon['discount_type'])
        ->setDiscountAmount($amount)
        ->setDiscountQty(1)
        ->setApplyToShipping($coupon['flag_is_free_shipping'])
        ->setTimesUsed($coupon['redemptions'])
        ->setWebsiteIds(array('1'))
        ->setCouponType(2)
        ->setCouponCode($code)
        ->setUsesPerCoupon(NULL);
$shoppingCartPriceRule->save();
}

?>

At first, the script only imported 100 coupons, but I saw error_log and discovered that the problem was memory_limit of php.ini. I incremented this memory limit and the script can import 170 coupons now.

How can i do to import the 20.000 coupons?

Thank you very much!

0
  1. Get csv data in batch -> solution
  2. What is the current memory limit though? :C I can hardly believe that you can process no more than 170 items...
| improve this answer | |

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.