Extract categories from Magento by a stand alone php script

Create a file MageRoot/shell/getCategories.php, and here is the code for this php script.

<?php

require_once 'abstract.php';

class Mage_Shell_Test extends Mage_Shell_Abstract
{
    public function run()
    {
        $this->getSubCategories(3);
        $this->getCatalogCategories();
    }

    // Get all categories up to 4 levels deep
    public function getCatalogCategories()
    {
    	$categories = Mage::getModel('catalog/category')->getCollection()
    	->addAttributeToSelect('*')
    	->addAttributeToFilter('level', 1)
    	->addAttributeToFilter('is_active', 1);
    	
    	//echo "number of categories: ". count($categories);
    	foreach($categories as $cate)
    	{
    		echo $cate->getName()."\n";
    		
    		$categoryIDs1=explode(',',$cate->getChildren());
    		//echo implode(",",$categoryIDs1);
    		foreach($categoryIDs1 as $catId1)
    		{
    			$category1 = Mage::getModel('catalog/category')->load($catId1);
    			$name = $category1->getName();
    			if(strlen($name)>0)
    				echo "***,".$category1->getName()."\n";
    			
    			$categoryIDs2 = explode( ',' , $category1->getChildren() );
    			foreach($categoryIDs2 as $catId2)
    			{
    				$category2 = Mage::getModel('catalog/category')->load($catId2);
    				$name = $category2->getName();
    				if(strlen($name)>0)
    					echo "***,***,".$category2->getName()."\n";
    				
    				$categoryIDs3 = explode( ",", $category2->getChildren());
    				foreach($categoryIDs3 as $catId3)
    				{
    					$category3 = Mage::getModel('catalog/category')->load($catId3);
    					$name = $category3->getName();
    					if(strlen($name)>0)
    						echo "***,***,***,".$category3->getName()."\n";
    					
    					$categoryIDs4 = explode(",",$category3->getChildren());
    					foreach($categoryIDs4 as $catId4)
    					{
    						
    						$category4 = Mage::getModel('catalog/category')->load($catId4);
    						
    						$name = $category4->getName();
    						if(strlen($name)>0)
    							echo "***,***,***,***,".$category4->getName()."\n";	
    					}
    				}
    			}
    		}
    	}
    }
    
    // print the category name and it's parent id as well as all the subcategories if they the category has them
    public function getSubCategories($cateId)
    {
    	$category = Mage::getModel('catalog/category')->load($cateId);
    	echo "NAME>>>".$category->getName()."PARENT ID>>>".$category->getParentId();
    	$categories=explode(',',$category->getChildren());
    	foreach($categories as $cat){
    		$category=Mage::getModel('catalog/category')->load($cat);
   			echo $category->getName()."\n"; 		
   		}    		
    }    
}
$shell = new Mage_Shell_Test();
$shell->run();

To run the script

php getCategories.php

To run the script and output the result in a csv file

php getCategories.php > categories.csv

Search within Codexpedia

Custom Search

Search the entire web

Custom Search