Tuesday 26 June 2012

How To Export and Import Category in Magento

For export category  create a simple php file catgory.php in root Folder.
<?php
    ini_set("memory_limit","1000M");
    require_once "app/Mage.php";
    umask(0);
    Mage::app();
    $category = Mage::getModel ( 'catalog/category' );
    $tree = $category->getTreeModel ();
    $tree->load();
    $ids = $tree->getCollection()->getAllIds();
    if ($ids) {
    $string='';
    $heading = '"store","categories","cat_id","is_active","meta_title","meta_keywords","meta_description","include_in_menu","is_anchor","description",';
    foreach ($ids as $id) {
    if($id>0)//start if removeroot category and default category .
    {

    $cate_cre = Mage::getModel('catalog/category');

    $cate_cre->load($id);
    $treeurl='';
    $cate_cre1=Mage::getModel('catalog/category')->load($id);
    $treeurl=$cate_cre->getName();
    if($cate_cre1->getParentId()>0)
    {
    for($i=0; ;$i++)
    {
    if($cate_cre1->getParentId()>0)
    {
    $abc=Mage::getModel('catalog/category')->load($cate_cre1->getParentId());
    $pCat=$abc->getName();
    if($abc->getId()>1){
    $treeurl=$pCat.'/'.$treeurl;
    }
    $cate_cre1=$abc;
    }
    else{
    break;
    }
    }
    }
    $store = "default";
    $string .='"'.$store.'","'.$treeurl.'","'.$id.'","'.$cate_cre->getIsActive().'","'.$cate_cre->getMetaTitle().'","'.$cate_cre->getMetaKeywords().'","'.$cate_cre->getMetaDescription().'","'.$cate_cre->getIncludeInMenu().'","'.$cate_cre->getIsAnchor().'","'.$cate_cre->getDescription().'"';
    $string.="\n";
    }//endof if removeroot category and default category .
    }
    $csv_output = $heading ."\n".$string;
    $filename = "Categories";
    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    header( "Content-disposition: filename=".$filename.".csv");
    print $csv_output;
    }
    ?>

After run this file at browser .u got a csv file-

After the export category you must need to import the categories and  you want to import the categories with previous category structure.For that work i craeted a folder ImpCat folder at app\code\local\
first i craete  file at a file Category.php  at app\code\local\ImpCat\Catalog\Model\Convert\Adaptera\

<?php
    class ImpCat_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']);
     /*$IsActive = $importData['IsActive'];*/
      $IsActive = $importData['is_active'];
     $IsAnchor =$importData['is_anchor'];
      $Description =$importData['description'];
       $IncludeInMenu=$importData['include_in_menu'];
       $MetaTitle=$importData['meta_title'];
    
       $MetaKeywords=$importData['meta_keywords'];
       $MetaDescription=$importData['meta_description'];
       $Image=$importData['image'];
       $URlkey=$importData['url_key'];
    
     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($IsActive)
             ->setIsAnchor($IsAnchor)
             ->setDisplayMode($dispMode)->save();
       
         $cat = Mage::getModel('catalog/category')->load($cat->getId());
         $cat->setIncludeInMenu($IncludeInMenu);
         $cat->setDescription($Description);
         $cat->setMetaTitle($MetaTitle).
       $cat->setMetaKeywords($MetaKeywords);
       $cat->setMetaDescription($MetaDescription);
       $cat->save();
    
      $cat = Mage::getModel('catalog/category')->load($cat->getId());
      $data['meta_keywords']=$MetaKeywords;
      $data['meta_title']=$MetaTitle;
      $data['meta_keywords']=$MetaKeywords;
      $data['meta_description']=$MetaDescription;
      $data['url_key']= $URlkey;
      $cat->addData($data);
      $cat->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;
     }

     /**
     * 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;
     }
     }
     }
    }

    ?>

There for need  config.xml file for configuration placed  at app\code\local\ImpCat\Catalog\etc\ -

<?xml version="1.0"?>
    <config>
     <global>
     <models>
     <catalog>
     <rewrite>
     <convert_adapter_category>ImpCat_Catalog_Model_Convert_Adapter_Category</convert_adapter_category>
     </rewrite>
     </catalog>
     </models>
     </global>
    </config>









Now craete  module controller file ImpCat_All.xml at app\etc\modules-

<?xml version="1.0"?>
    <config>
     <modules>
     <ImpCat_Catalog>
     <codePool>local</codePool>
     <active>true</active>
     </ImpCat_Catalog>
     </modules>
    </config>






then, create a  dataflow advanced profile into -admin/system/Import Export/Dataflow Advanced Profile and give the Profile Name is 'category import'and
its Actions XML  is-





<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>



after create import categoryextension you goes to admin system->permission->roles->Administrators ->Role Users

click on Save Role.Then Flush magento Cache.
Then downloaded  Categories.csv put Categories.csv into var/import/
and removed cat_id colums from csv and
remove first two rows

and remove all Default Category/ from categories colunn in Categories.csv.
Now you go to again- admin/system/Import Export/Dataflow Advanced Profile  run 'category import' profile>Run Profile>click 'Run Profile in Popup' import of category now start and automatically created category. Now you fill happy.Click here to download
click for csv

 http://www.bluehorse.in/Uploads/cat.rar

and click for extension  http://www.bluehorse.in/Uploads/ImpCat_All.rar
and
http://www.bluehorse.in/Uploads/ImpCat.rar





23 comments:

  1. I am getting the following error when i run the profile:

    Method "parse" not defined in adapter catalog/convert_adapter_category.

    Please advise asap

    ReplyDelete
  2. My Also same error occurs ..
    Method "parse" not defined in adapter catalog/convert_adapter_category.

    I disable the Cache and as well flushed magento and cache storage but it didn't work.

    Please help

    ReplyDelete
  3. Is it possible to import multi-language store categories with this script? Few times I gone through same procedure as you said, to import categories, but when I run profile, I still get this error:
    “Declared adapter catalog/convert_adapter_category not found”
    I would say that anyone who tried and failed with this script should retry with Store Manager module which worked for me perfectly.

    ReplyDelete
  4. My Also same error occurs ..
    Method "parse" not defined in adapter catalog/convert_adapter_category.

    I disable the Cache and as well flushed magento and cache storage but it didn't work.

    Please help

    ReplyDelete
  5. Same Error: Method "parse" not defined in adapter catalog/convert_adapter_category.


    Please Help

    ReplyDelete
  6. This comment has been removed by a blog administrator.

    ReplyDelete
    Replies
    1. Hello,
      I've the same problem ..
      Method "parse" not defined in adapter catalog/convert_adapter_category.
      Your fix doesn't help :/
      Any idea ? Somebody used that script ?
      @Autor, Can you renew download link ?

      Delete
  7. I'm getting the same "Method "parse" not defined in adapter catalog/convert_adapter_category" error.

    This looks like a wonderful script. The export works great. Wish I could get the import to work too.

    Andy ideas.

    ReplyDelete
  8. Hey all,

    The problem you are getting is because a misspeling in the folder above.

    It says:
    app\code\local\ImpCat\Catalog\Model\Convert\Adaptera\

    And supposed to be:
    pp\code\local\ImpCat\Catalog\Model\Convert\Adapter\

    Hope it helps

    ReplyDelete
    Replies
    1. Nope. I renamed the folder - to Adapter , forbid cache and flushed it, reindexed files.. Still not works..

      Any ideas ?

      Delete
  9. Hello,

    Thanks for the tutorial,

    How can i export categories when i have 3 store views (ENG, DE and FIN) and i want to export all 3 separate store views so i can translate all the category names.'

    Or is there easier solution for this?

    Thank You,
    Martti

    ReplyDelete
  10. I'm getting "Fatal Error" : Call to undefined method ImpCat_Catalog_Model_Convert_Adapter_Category::getStoreById() in /app/code/local/ImpCat/Catalog/Model/Convert/Adapter/Category.php on line 42

    Any ideas ?

    Thanks,

    Bill

    ReplyDelete
    Replies
    1. I have the same problem, did you solve it?

      Delete
  11. I want to export categories and subcategories from live server, but when I followed your step and tried to run the category.php it is getting redirected to home page of frontend. Please help.!! Even i have kept the file(category.php) in root folder i:e site_name/public_html/
    PLEASE seriously need help

    ReplyDelete
  12. Hey Andre
    even after correcting spelling of adapter it is not working.
    This is what i get :-


    Starting profile execution, please wait...
    Warning: Please do not close the window during importing/exporting data

    Starting Mage_Dataflow_Model_Convert_Adapter_Io :: load
    Loaded successfully: "/var/www/esolz.co.in/public/lab2/santblanc/var/import/Categories.csv".
    Starting Mage_Dataflow_Model_Convert_Parser_Csv :: parse
    Method "parse" not defined in adapter catalog/convert_adapter_category.
    Finished profile execution.

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. Hello Andre,
    I found this error.Please help me to resolve this error
    Starting Mage_Dataflow_Model_Convert_Parser_Csv :: parse
    Method "parse" not defined in adapter catalog/convert_adapter_category.
    Finished profile execution.

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. Its error :

    " Method "parse" not defined in adapter catalog/convert_adapter_category. "

    I renamed the folder as Andre advised, but still nothing seems to be ok..

    Any ideas ?

    Thx

    ReplyDelete
  17. catgory.php in root Folder means in which folder did i put this code

    ReplyDelete

Note: only a member of this blog may post a comment.