Created
June 9, 2014 09:30
-
-
Save dhargitai/7346291438037da00d84 to your computer and use it in GitHub Desktop.
Import newsletter subscribers into Magento
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$magentoRootPath = './public'; | |
require_once $magentoRootPath . '/shell/abstract.php'; | |
class SubscriberImportFromCsv extends Mage_Shell_Abstract | |
{ | |
protected $_fileName; | |
protected $_emailFieldIndex; | |
protected $_hasHeaderRow; | |
protected $_defaults = array( | |
'store_id' => 1, | |
); | |
public function __construct() | |
{ | |
parent::__construct(); | |
$this->_defaults['subscriber_status'] = Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED; | |
if ($this->getArg('h') || | |
$this->getArg('help') || | |
count($this->_args) == 0) { | |
echo $this->usageHelp(); | |
return 1; | |
} | |
$this->_fileName = $this->getArg('f') ?: 'subscribers.csv'; | |
$this->_emailFieldIndex = $this->getArg('ei') ? (int)$this->getArg('ei') : 0; | |
$this->_hasHeaderRow = $this->getArg('hh') ? (int)$this->getArg('hh') : FALSE; | |
} | |
function run() | |
{ | |
if (($handle = fopen($this->_fileName, "r")) !== FALSE) { | |
$count = 0; | |
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { | |
if ($this->_hasHeaderRow) { | |
$this->_hasHeaderRow = FALSE; | |
continue; | |
} | |
$email = strtolower($data[$this->_emailFieldIndex]); | |
$model = Mage::getModel('newsletter/subscriber')->setImportMode(true); | |
$model->subscribe($email); | |
$subscriber = $model->loadByEmail($email); | |
$subscriber | |
->setStoreId($this->_defaults['store_id']) | |
->setStatus($this->_defaults['subscriber_status']) | |
->save(); | |
$count++; | |
} | |
fclose($handle); | |
} | |
echo "\nDone (processed rows count: " . $count . ")\n"; | |
} | |
public function usageHelp() | |
{ | |
return <<<HELP | |
SYNOPSIS | |
php -f subscriberImportFromCsv.php | |
php -f subscriberImportFromCsv.php [-- [OPTIONS...]] | |
DESCRIPTION | |
This script can import subscribers from CSV file. | |
OPTIONS | |
-h | |
-help | |
print this usage and exit | |
-f [file] | |
import customers from csv file, if source file not specified or not found uses defined in config.xml | |
default: subscribers.csv | |
-ei | |
specify which column stores the email addresses in the CSV file (starting from 0) | |
default: 0 | |
-hh | |
specify whether there is a header row without data (giving value 1) or not (giving value 0) | |
default: 0 | |
EXAMPLE | |
php -f customerImportFromCsv.php -- -f subscribers.csv | |
HELP; | |
} | |
} | |
$main = new SubscriberImportFromCsv(); | |
$main->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment