Export Magento categories and IDs to CSV

On occasion, you’ll find yourself needing to know the ID number which corresponds to each category. You can manually find this, as it’s show alongside the category name in Catalogue -> Manage Categories, but if you need them all, this isn’t the most efficient way of going about it. What follows in this post is a simple script to export Magento categories to a CSV file for you to download and use as you see fit. We start by hooking into Magento – the file is going to be uploaded to the web root of the installation, but if you want to upload it anywhere, just change the reference to app/Mage.php in the first line.

<?php
require_once 'app/Mage.php';
Mage::app();
$allCategories = Mage::getModel ( 'catalog/category' );
$categoryTree = $allCategories->getTreeModel();
$categoryTree->load();
$categoryIds = $categoryTree->getCollection()->getAllIds();	

If we’ve got categories to play with, we then create the CSV file (this is in the var/importexport folder by default, but can be changed to wherever you want) :

if ($categoryIds) {
	$outputFile = "var/importexport/categories-and-ids.csv";
	$write = fopen($outputFile, 'w');

Then we loop through each category ID in the collection, and write its name and ID to the CSV file :

	foreach ( $categoryIds as $categoryId ) {
		$data = array($allCategories->load($categoryId)->getName(), $categoryId);
		fputcsv($write, $data);
	}
}

Finally we then close the CSV file :

fclose($write);
?>

And that’s it – upload the file to your Magento installation, hit the file in your browser (you’ll not get any on-screen output) and your exported Magento categories will be ready to download from the var/importexport folder.

42 comments

  • Matt

    Hello,

    Brilliant piece of code. But I’m wondering how would you export categories on different web stores?

    • Giles Bennett (author)

      Matt,

      Try setting the store ID in the fourth line

      Mage::app()->getStore()->setId(Mage_Core_Model_App::ADMIN_STORE_ID);
      

      Kind regards,

      Giles

  • Daryl

    Giles,

    Having trouble getting this to work. The file is in the /web directory and when I visit the domain.com/categories.php nothing displays as expected, however there is no file in var/export

    Have I missed something?

    Thanks

    • Giles Bennett (author)

      Is the var directory writeable? And does the var/importexport folder exist, as the script may not create it if it doesn’t exist?

      Kind regards,

      Giles

  • David Radovanovic

    Giles, I’m searching for a way to export/import specific categories with ID and images. Can your script be customized to include images for specific Cat ID? Thanks for sharing. P.S. Your script works flawlessly in 1.9.2.4.

    • Giles Bennett (author)

      David,

      I’ll not do all the work for you, but this should give you enough to be going on with. In essence, the category IDs that you want to export go into the $desiredCategories array. If the category matches, then it will echo the Image and Thumbnail file names (they’re kept in media/catalog/category) for the category concerned.

      Combine it with the CSV-generating elements from the code above and you should get to where you want to be.

      <?php
      require_once 'app/Mage.php';
      Mage::app();
      $category = Mage::getModel ('catalog/category');
      $categoryTree = $category->getTreeModel();
      $categoryTree->load();
      $categories = $categoryTree->getCollection();	
      $desiredCategories = array(231,134,190);
      foreach ($categories as $acategory) {
      	$categoryID = $acategory->getId();
      	if(in_array($categoryID, $desiredCategories)) { 
      		$fullCategory = $category->load($categoryID);
      		echo "Main image : " . $fullCategory->getImage() . "\n";
      		echo "Thumbnail image : " . $fullCategory->getThumbnail() . "\n";
      	}
      }
      ?>
      

      Kind regards,

      Giles

  • Colin

    Thanks so much! Just what I needed.

    • Giles Bennett (author)

      Colin,

      You’re welcome, glad it helped.

      Kind regards,

      Giles

  • Christer Johansson

    Hi!
    First, thank you for this excellent little script, works excellent!
    Now to my little issue.
    As I have exported another non-Magento stores categories, and my spreadsheet now have all sub-categories with matching parents id.
    You script shows the ID’s of all categories, and it’s good. But I would love to have parent ID of sub-category as well.
    Can we export all categories, and then add all sub-categories parent-id?

    I am basically looking to get a structure for Excel, and then organize my 250 categories into a CSV for import to Magento.

    • Giles (author)

      Christer,

      You would need to edit the script as follows. Instead of :

      $data = array($allCategories->load($categoryId)->getName(), $categoryId);
      

      you would want to have :

      $parentId = $allCategories->load($categoryId)->getParentId();
      $data = array($allCategories->load($categoryId)->getName(), $categoryId, $parentId);
      

      The new line gets the category’s ParentId, the amended second line writes that into the third column of the CSV.

      Kind regards,

      Giles

      • Christer Johansson

        Ok, thanx for help! Really appreciate it! ๐Ÿ™‚
        I’ve tested it, and I get my categories into a csv file, and they all show “default category” as 1 , I’m gonna have to experiment with this a bit.
        Basically, I want to build a file containing all neccessary info to export/import the categories with their ID’s so I can move stuff to a new store later.

        • Giles (author)

          Christer,

          Good luck.

          Kind regards,

          Giles

          • Christer Johansson

            Hi again,
            I modified this script, and it works great now. I get the id’s for categories and their parent. I am however struggling really hard to get them back into a fresh installation of Magento 1.9.2.2. I tried various modules, scripts and whatnot…none work as intended.
            I have here a script that imports the exported CSV, but I only get the root category to show up in admin. All other categpries are no where to be seen, except I can see them in the DB, and don’t know how to properly import them.

            I created/modified a script I found, I’ve pasted it on Pastebin: http://pastebin.com/z34S8wzg
            I would be forever happy if you could have a look at it and see if you spot any errors.
            My CSV is structured like this, first column is name, second column is catId, and third column is parentId
            “Root Catalog”,1,0

          • Giles (author)

            Christer,

            We can take a look at the script, but whilst we offer feedback and suggestions on our blog posts, I think that advising on a separate script goes beyond that, so it would have to be chargeable work – email us at info@hummingbirduk.com if you wish.

            Kind regards,

            Giles

          • Christer Johansson

            Hi again! ๐Ÿ™‚
            I actually managed to figure it out after hours of swearing over Magento.. ๐Ÿ˜€
            Here’s how I fixed it, http://pastebin.com/xAsusjj0

            It now imports all of the CSV correct. I export it with your script, make any modification I need in the CSV through OpenOffice Calc, and import it with my script to the new store and keep all IDยดs. Now I can transfer all products and categories correct from old store to new.

            Thank you for your help in this article, it was very useful. I will now move on to your article on how to change SKU’s. ๐Ÿ˜›

            Merry X-Mas!

          • Robert Paduraru

            Thanks Christer! You saved me with this script, but for those who want to use this script replace on while loop $line with $column to make it work.

  • jackson

    Thank you very much for this. Very helpful

    • Giles (author)

      Jackon,

      No problem.

      Kind regards,

      Giles

  • David

    Thanks Giles – turned a two hour job into a two minute one!

    • Giles (author)

      David,

      No problem.

      Kind regards,

      Giles

  • Vivek

    I want to export only subcats of a particular category, how can I do with this script ?

    Reply fast please

    • Giles (author)

      Vivek,

      You would filter the original category collection.

      Kind regards,

      Giles

      • Felipe

        And How do I do that on your code, the filter would be this: “$allCategories = Mage::getModel ( ‘catalog/category’ );” ?

        My doubt is the same from the Vivek, I wish to export a group of category and its sub-categories, separated from the others one

        • Giles Bennett (author)

          Felipe,

          You would need to change the code to load only the parent category which you want to export, rather than all categories. Look into adding filters to collections – that should take you where you want to go.

          Kind regards,

          Giles

  • Adam Cook

    Excellent, thank you!

  • Manoj

    Categories ID Export perfectly. Now I want import this csv in another magento store. How can we do this?

    • Giles (author)

      Manoj,

      You’d need to write a script to create the categories based on the information exported.

      Kind regards,

      Giles

  • Jaby

    Great tip! i’m actually playing with your code and works fine ๐Ÿ™‚
    A little question, what about getting the URL of each category? I’ve changed the data array and put “$allCategories->load($categoryId)->getUrl()” but always give me the same url (like if i was at root url/folder)

    Great tutorial, Thanks
    All the best,
    Jaby

    • Giles (author)

      You would probably want to amend the loop to load the full category information, then pull it from that. Buy you’ll only get the category’s URI, rather than the full URL to the category, I think, as the full URL is built from other categories’ URLs.

      Kind regards,

      Giles

      • Jaby

        At the moment i was changing the code, to “$allCategories->load($categoryId)->getUrlPath()” and adding manually the baseURL to get the full URL.

        Thanks for ur reply!
        Jaby

  • Ryan

    Hey Giles thank you for this script! I have one question though – I have several same-name subcategories that have different parent categories so I can’t tell which one goes with which…is there a way to include the category path? e.g. Apparel/Men’s/T-Shirts (as there is a ‘T-Shirts’ category under Women’s & Kids)

    • Giles (author)

      Ryan,

      Well, within the loop where we’re getting the category ID, we’re currently only passing two bits of data into the $data array :

      1. the category name – $allCategories->load($categoryId)->getName()
      2. the category ID – $categoryId

      There is the possibility of getting the “path” of the category, which includes all its parents, but in the form of IDs, so $allCategories->load($categoryId)->getPath() would return something like 1/5/29/201, where each of the numbers represents a category in the path leading down to the current category in the loop.

      If you were to feed that into a variable, then split the variable into an array based on the presence of the “/”, you could then loop through the array and use the same methodology that we’re using at the moment to get one name from the an ID to get each of the names which corresponds to each of the IDs in the path. You could then concatenate those into a new variable, and pass that to the $data array rather than just the single category name. That would then give you the ID and the full path, in text form.

      Hope that helps.

      Kind regards,

      Giles

  • AW

    THANK YOU!! Worked easily and quickly. In case anyone is wondering, yes this does work for Magento Enterprise. Again, Thank You!!!

    • Kim

      Dear Giles,
      Thank you for your kindness to share this piece of code. I’m just a beginner, don’t know much about coding. I’d like to get the category/subcategory ‘s name and the full path , plus the ID.
      Please show me how to combine getPath() & getName() code to achieve what I wanted

      foreach ( $categoryIds as $categoryId ) {
      $data = array($allCategories->load($categoryId)->getName(), $categoryId);
      fputcsv($write, $data);
      }
      }
      Thanks for your help

      • Giles (author)

        Kim,

        The $data array is just a comma separated list of values that is then written to the CSV with the fputcsv command. To add to the array, therefore, just add a comma separated item. So if getPath() returns the path, then you would simply change the line to :

        $data = array($allCategories->load($categoryId)->getName(),$allCategories->load($categoryId)->getPath(), $categoryId);
        

        That should then output the Name, Path and ID.

        Kind regards,

        Giles

  • Angelo

    One more thanks from Brazil, Giles! Cheers!

  • Yogi

    Great Tutorial

    Thanks

  • redd

    how would i go about importing these categories on my test site?

    • Giles (author)

      You would need to write a separate script which parses the CSV and creates the categories based on that information

      Kind regards,

      Giles

  • Arthur

    Worked like a charm! Thanks!

    Added to fav’s! Awesome work!

  • Sean

    Many thanks Giles that works perfectly!

    • Giles (author)

      Sean,

      No problem!

      Kind regards,

      Giles

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to talk to us about your project?