Tuesday, June 28, 2011

Replicate Category Tree from one Magento to Other Magento (Import category in Magento)

Recently I was working on Magento migration where I have to migrate magento shop from one server to other and create an identical shop on other server. Here time was the concern. So instead of creating categories manually I decided to create to replicate whole category tree with same category ids on other server. As next turn was to import product and keep in the same category. I used Magento API to get category tree from old Magento and traversed through it to create categories in new Magento. Check the following code.

I used recursive function to traverse the whole tree.


$flag = 1;
$client=new SoapClient('http://www.oldmagentodomain.com/api/soap/?wsdl');
$sessionId = $client->login('myAPIUserName','myApiKey');

$categoryTree= $client->call($sessionId, 'category.tree');

$currentCategory = $categoryTree['children'];


importCategory($currentCategory,$client); //This starts the import.



function importCategory($currentCategory,$client)
{

      $count= count($currentCategory);
      for($i=0; $i<$count; $i++)
      {
           $categoryId = $currentCategory[$i]['category_id'];
           $categoryInfo = $client->call($sessionId, 'category.info',$id);
   
           if($flag == 1)
           {
               $rootParentCategory = 1;
               $flag = 0;
           }
           else
           {
                $rootCategory = $categoryInfo ['parent_id'];
           }

                             
           $newCategory = new Mage_Catalog_Model_Category();                      
           $newCategory ->setName($categoryInfo ['name']);
           $newCategory ->setUrlKey($categoryInfo ['url_key']);
           $newCategory ->setLevel($categoryInfo ['level']);
           $newCategory ->setIsActive($categoryInfo ['is_active']);
           $newCategory ->setIsAnchor($categoryInfo ['is_anchor']);
           $newCategory ->setId($categoryInfo ['category_id']);

                               
           $parentCategory = Mage::getModel('catalog/category')->load($rootCategory);
           if($parentCategory)
           {
                $newCategory ->setPath($parentCategory->getPath()."/");                              
           }
            else
           {      
                 $newCategory ->setPath('');                                
            }

           $newCategory ->save(); 

           $childCategories = $currentCategory[$i]['children'];

           if($childCategories)
           {
               importCategory($childCategories,$client);
           }



     }
}

I hope this will help you. Now next post would be about importing products via Magento API. Stay tuned.

Thanks.

No comments:

Post a Comment