Magento
How to Export Categories/Subcategories from x-cart to Magento?
by Raza on Mar.21, 2011, under Magento
Hi guys!
I just started working in magento a few days back. One of the tasks was to import categories data from x-cart to magento. So lets get started:
- First create a file called func.export_magento.php in the folder include/func of the x-cart installation, and write the following code in it.
<?php if ( !defined('XCART_START') ) { header("Location: ../"); die("Access denied"); } function getSubCategoriesCSV($catid,$cattitle) { global $sql_tbl,$config; $strCSV = ''; $newline = "\n"; $categories = func_query("select * from $sql_tbl[categories] where parentid=$catid"); if(sizeof($categories)>0) { foreach($categories as $category) { $ctitle = '/'.$category["category"]; if(getSubCategoriesCSV($category["categoryid"],$cattitle)=='') { $strCSV .= '"default","'.$cattitle.$ctitle.'"'.$newline; } else { $strCSV .= '"default","'.$cattitle.$ctitle.'"'.$newline; $strCSV .= getSubCategoriesCSV($category["categoryid"],$cattitle.$ctitle).$newline; } } } return $strCSV; } ?> - Then create another file called export_magento.php in the admin folder of the x-cart installation. Write the following code in it:
<?php require "./auth.php"; require $xcart_dir."/include/security.php"; require $xcart_dir."/include/categories.php"; x_load("export_magento"); $newline = "\n"; $output = ''; $output .= '"store","categories"'; $output .= "$newline"; $parentCategories = func_query("select * from $sql_tbl[categories] where parentid=0 order by product_count desc;"); foreach($parentCategories as $pcat) { $output .= '"default","'.$pcat["category"].'"'; $output .= $newline; $csvstring = getSubCategoriesCSV($pcat["categoryid"],$pcat["category"]); $output .= $csvstring; $output .= $newline; } @mkdir($xcart_dir.'/export',0777,true); $expfile = $xcart_dir."/export/Categories.csv"; $fp = @fopen($expfile,'w+'); @fwrite($fp,$output); @fclose($fp); if(file_exists($expfile)) { header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename='.basename($expfile)); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . filesize($expfile)); ob_clean(); flush(); readfile($expfile); exit; } $smarty->assign("main","magento"); # Assign the current location line $smarty->assign("location", $location); @include $xcart_dir."/modules/gold_display.php"; func_display("admin/home.tpl",$smarty); ?>The last four lines of code is for theme configuration and is for x-cart 4.1.8 gold. Change it accordingly for your version of x-cart.
- The above code will write the categories data into a CSV file, and will let you download the file.
- Before exporting the data to magento, you should install and configure magento on your system. Here is a guide that i previously wrote on installation in windows with xampp..
- When you have installed magento, login into the backend. Then goto System->Import/Export->Dataflow – Advanced Profiles. Click Add New Profile to add a profile.
- In the Profile Name textbox, write Import Categories. In the Actions XML textarea, write the following code:
<action type="dataflow/convert_adapter_io" method="load"> <var name="type">file</var> <var name="path">var/import</var> <var name="filename"><![CDATA[Categories.csv]]></var> <var name="format"><![CDATA[csv]]></var> </action> <action type="dataflow/convert_parser_csv" method="parse"> <var name="delimiter"><![CDATA[,]]></var> <var name="enclose"><![CDATA["]]></var> <var name="fieldnames">true</var> <var name="store"><![CDATA[0]]></var> <var name="number_of_records">1</var> <var name="decimal_separator"><![CDATA[.]]></var> <var name="adapter">catalog/convert_adapter_category</var> <var name="method">parse</var> </action>.
- Now click Save Profile to save the profile.
- Now upload the file into var/import folder of the magento installation.
- Now a create folder called MyApp in the app/code/local folder of magento installation. Create the following folders in the myappfolder also:
- Catalog/Model/Convert/Adapter/
- Catalog/etc/
- In the Catalog/Model/Convert/Adapter/ folder, create a file Category.php, and write the following code in it.
class MyApp_Catalog_Model_Convert_Adapter_Category extends Mage_Eav_Model_Convert_Adapter_Entity { protected $_categoryCache = array(); protected $_stores; /** * Category display modes */ protected $_displayModes = array( 'PRODUCTS', 'PAGE', 'PRODUCTS_AND_PAGE'); public function parse() { $batchModel = Mage::getSingleton('dataflow/batch'); /* @var $batchModel Mage_Dataflow_Model_Batch */ $batchImportModel = $batchModel->getBatchImportModel(); $importIds = $batchImportModel->getIdCollection(); foreach ($importIds as $importId) { //print '<pre>'.memory_get_usage().'</pre>'; $batchImportModel->load($importId); $importData = $batchImportModel->getBatchData(); $this->saveRow($importData); } } /** * Save category (import) * * @param array $importData * @throws Mage_Core_Exception * @return bool */ public function saveRow(array $importData) { if (empty($importData['store'])) { if (!is_null($this->getBatchParams('store'))) { $store = $this->getStoreById($this->getBatchParams('store')); } else { $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store'); Mage::throwException($message); } } else { $store = $this->getStoreByCode($importData['store']); } if ($store === false) { $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']); Mage::throwException($message); } $rootId = $store->getRootCategoryId(); if (!$rootId) { return array(); } $rootPath = '1/'.$rootId; if (empty($this->_categoryCache[$store->getId()])) { $collection = Mage::getModel('catalog/category')->getCollection() ->setStore($store) ->addAttributeToSelect('name'); $collection->getSelect()->where("path like '".$rootPath."/%'"); foreach ($collection as $cat) { $pathArr = explode('/', $cat->getPath()); $namePath = ''; for ($i=2, $l=sizeof($pathArr); $i<$l; $i++) { $name = $collection->getItemById($pathArr[$i])->getName(); $namePath .= (empty($namePath) ? '' : '/').trim($name); } $cat->setNamePath($namePath); } $cache = array(); foreach ($collection as $cat) { $cache[strtolower($cat->getNamePath())] = $cat; $cat->unsNamePath(); } $this->_categoryCache[$store->getId()] = $cache; } $cache =& $this->_categoryCache[$store->getId()]; $importData['categories'] = preg_replace('#\s*/\s*#', '/', trim($importData['categories'])); if (!empty($cache[$importData['categories']])) { return true; } $path = $rootPath; $namePath = ''; $i = 1; $categories = explode('/', $importData['categories']); foreach ($categories as $catName) { $namePath .= (empty($namePath) ? '' : '/').strtolower($catName); if (empty($cache[$namePath])) { $dispMode = $this->_displayModes[2]; $cat = Mage::getModel('catalog/category') ->setStoreId($store->getId()) ->setPath($path) ->setName($catName) ->setIsActive(1) ->setIsAnchor(1) ->setDisplayMode($dispMode) ->save(); $cache[$namePath] = $cat; } $catId = $cache[$namePath]->getId(); $path .= '/'.$catId; $i++; } return true; } /** * Retrieve store object by code * * @param string $store * @return Mage_Core_Model_Store */ public function getStoreByCode($store) { $this->_initStores(); if (isset($this->_stores[$store])) { return $this->_stores[$store]; } return false; } public function getStoreById($id) { $this->_initStores(); /** * In single store mode all data should be saved as default */ if (Mage::app()->isSingleStoreMode()) { return Mage::app()->getStore(Mage_Catalog_Model_Abstract::DEFAULT_STORE_ID); } if (isset($this->_storesIdCode[$id])) { return $this->getStoreByCode($this->_storesIdCode[$id]); } return false; } /** * Init stores * * @param none * @return void */ protected function _initStores () { if (is_null($this->_stores)) { $this->_stores = Mage::app()->getStores(true, true); foreach ($this->_stores as $code => $store) { $this->_storesIdCode[$store->getId()] = $code; } } } } ?>Also copy this file into app/code/core/Mage/Catalog/Model/Convert/Parser/ folder.
- Create a file config.xml in the MyApp/Catalog/etc/ folder. Write the following code in it:
<?xml version="1.0" encoding="UTF-8"?> <config> <global> <models> <catalog> <rewrite> <convert_adapter_category>MyApp_Catalog_Model_Convert_Adapter_Category</convert_adapter_category> </rewrite> </catalog> </models> </global> </config> - Now create another file MyApp_All.xml in the app/etc/modules folder,and write the following code in it.
<?xml version="1.0"?> <config> <modules> <MyApp_Catalog> <codePool>local</codePool> <active>true</active> </MyApp_Catalog> </modules> </config> - Now goto System->Import/Export->Dataflow – Advanced Profiles. Click on the profile you just created in step 6. Click Run Profile. Now click Run Profile in Popup. This will open a popup window, which will start importing the categories data into magento from the CSV file you downloaded from the x-cart script in step 1 & 2.
- In case of any issues, please dont hestitate to comment…