Quick script to export Magento categories with IDs

If you are after a quick method to get all the category ID's for your categories for some Excel lookups (for new data imports), then this quick PHP script should help you out:


define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';

$category = Mage::getModel('catalog/category');
$tree = $category->getTreeModel();
$ids = $tree->getCollection()->getAllIds();

if ($ids) {
    $file = "var/import/catwithid.csv";
    file_put_contents($file, "catId, catNamen");
    foreach($ids as $id) {
        $string = $id . ', ' . $category->load($id)->getName() . "n";
        file_put_contents($file, $string, FILE_APPEND);

Simply save the above code in a PHP file in the base Magento directory of your store, and visit the URL in your web browser, simples!

  • Pingback: Quick script batch create Magento categories | Manchester Magento web design, development, Magento hosting and aftercare :: sonassi()

  • Moshe

    thank you this worked great

  • AB

    Can anyone tell me the exact path where to copy this php file and by what name the php file should store.
    I am using the localhost machine . PLease tell me the path where to save this file exactly.

    • Just drop it into your Magento root directory (where the app/media/var directories are). Then access via PHP-CLI or Web browser.

  • AB

    HEllo BEn,
    Thanks for the quick reply,
    Can u please tell me the further procedure to export the category csv. Is it by going to Admin->System->Import/export->Profiles. How i should exactly do can you please help me by writing the steps..
    Thanks in Advance

    • This is just a quick script (no real integration with Magento), so you just run it standalone ie.


      or via command line PHP

      #> php ./quickCatCreate.php

      Then it writes a file to wherever the variable is set …

      $file = β€œvar/import/catwithid.csv”;

  • Pingback: Quick script to mass enable categories in Magento | Manchester Magento web design, development, Magento hosting and aftercare :: sonassi()

  • Alex

    Hi Ben,
    I managed to make yur script work - thanks. My question is how do I edit this code to make it include subcategories? EG. I have 3 backpack subcategories each under different brands but looking at the CVS file, I can't distinguish which backpack subcategory id belongs with each brand.
    Do you have code to make this happen?
    Would really appreciate it!

    • The above code is great.
      But i have done some modification to it to get parent id and level.
      You can use this code and insert this data in temp table and you can get subcategories
      using parent_category_id.

      $ids = $tree->getCollection()->getAllIds();
      if ($ids) {
      $file = "var/import/catwithid.csv";
      file_put_contents($file, "catId,catName,catParent_id,catLeveln");//two more fields
      foreach ($ids as $id) {
      // ADDED BY Pragnesh Karia starts
      $pk = Mage::getModel('catalog/category');
      $string = $pk->getId() . ',' . $pk->getName() . ',' . $pk->getParentId() . ',' . $pk->getLevel() . "n";
      // ADDED BY Pragnesh Karia ends

      //$string = $id . ', ' .$category->load($id)->getName().','.$category->load($id)->getParentId().','.$category->load($id)->getLevel() ."n";

      file_put_contents($file, $string, FILE_APPEND);

  • Thanks !!!

    That worked perfectly.

  • Finees

    Awesome! Now, only if it was this easy to import the categories back into Magento... life would be better πŸ™‚

    • There is an easy way. I've been meaning to post all our scripts, but have been too busy to do it, I'll try to update the blog with more soon!

  • thanks ! it works well !but I still want to know if I can import the catagories easily !

    • I've got a script for category creation, I just haven't had the time to blog it yet. I'll add it to my list of jobs to do.

  • Yes, it works well !

    but, i have a problem that i want to export one catelog and products of this catelog from magento A which has many sub catelogs to magento B which that only one catelog that i want it .

    do you have any ideas?

    3Q anyway~

  • Hi, I have done exactly as above, but when I run the script, nothing seems to happen... I have added an echo statement after the script and it appears to be working, but no file is created. any ideas?
    I am using ver

    • Hi Hugh,

      I really doubt this would work on 1.5 - it was originally coded for 1.3/1.4 releases - the DB schema has changed a lot since then!

      • Ok, Ben, thanks for the heads up, will try and figure out another way...


        • Just a quick note, this does work in 1.5, I just needed to create the import folder manually first... Doh!

  • Bo

    Thanks, this helped me out!

  • Ally

    thanks for this post - Really useful - I want to know if i can export the category data within Magento as part of the product export. I would have thought this was possible but I can't seem to do it .

    Any ideas?!

    • Hi Ally,

      How do you mean exactly "as part of the product export"? The only shared element between categories and products is the ID - are you wanting the category names exported with the product export? If so, you could use an advanced profile and write an adapter to interface the two.

      Bear in mind, it exports IDs for a reason, categories can share the same name but be in a different position in the category tree, whereas an ID is unique.

  • Worked great for me on Magento 1.4.2!

    I tweaked one line of your script to deal with categories that contain commas in the name. Line #17 I changed to:

    $string = $id . ', ' . '"' .$category->load($id)->getName() . '"' . "n";

  • Jerick


  • Akos

    Thanks!! Saved a ton of time.

  • mjamb

    thx...works great on 1.5.1

  • Thanks It Helped me a lot!

  • Nice tip!
    Here is a modification we made to get also the full path to the categories.
    Also added some echoes to see what's going on.
    Please disregard the dirty code.. ^_^

    define('MAGENTO', realpath(dirname(dirname(__FILE__))));
    require_once MAGENTO . '/app/Mage.php';

    $category = Mage::getModel ( 'catalog/category' );
    $tree = $category->getTreeModel ();
    $tree->load ();

    $nodes = $tree->getNodes();

    if ($nodes) {
    $file = "var/import/cats.csv";
    echo ""catId","catName","catPath"n";

    foreach ( $nodes as $node ) {

    $id = $node->getId();
    $name = $category->load($id)->getName();

    $path = '';
    $parents = $node->getPath();
    foreach ($parents as $i=>$parent) {
    $parent_id = $parent->getId();
    $parent_name = $category->load($parent_id)->getName();
    $path = $parent_name . ($i?'/':'') . $path;

    $string = '"'. $node->getId() . '","'. $name . '","'. $path . ""n";
    echo "$stringn";

    • this didn't work for me... It was placed in root folder of Magento dir.
      Switched first line to: define('MAGENTO', realpath(__DIR__));
      (get the current directory - Added in PHP 5.3.0 ) and it worked like a charm!

  • tried using the script. copied it to where my app folder is but got nothing just a blank screen.

    • Hi Finley,

      You don't put the script into the app folder. You need to put it into a sub-folder of the Magento root directory (but not a protected dir like app/var etc.)

      You'll likely not see any errors if you have error display turned off in your PHP settings.

      Try again - the script is tried and tested, you're making a mistake somewhere.

  • dezire

    Hi everybody,

    I need Help!

    how i do this? i need export all the products in stock and I need the following information

    I’d like to export the whole name of the category, not just the numbers of them


    How i do that export?


    • Do you need to do it regularly or just one-off? If the latter, just use the DataFlow - its slow, but will work without any scripts/code changes.

  • Wise

    Hi Ben, i put it the file in to root folder, then i went to see it but i see a blank page? plz can you tel me what im doing wrong?
    I put it also in a sub folder includes but still i can not see the anything.


    • I would suggest checking your PHP error log.

  • MeoMap

    ( ! ) Fatal error: Uncaught exception 'Exception' with message 'Warning: file_put_contents(var/import/cats.csv) [function.file-put-contents]: failed to open stream: No such file or directory in E:xampphtdocstigopromostpromoshometpromospublic_htmlvartest.php on line 14' in E:xampphtdocstigopromostpromoshometpromospublic_htmlappcodecoreMageCorefunctions.php on line 245
    ( ! ) Exception: Warning: file_put_contents(var/import/cats.csv) [function.file-put-contents]: failed to open stream: No such file or directory in
    File test.php in var, and this is my error, please help me to resolve it πŸ™

    E:xampphtdocstigopromostpromoshometpromospublic_htmlvartest.php on line 14 in E:xampphtdocstigopromostpromoshometpromospublic_htmlappcodecoreMageCorefunctions.php on line 245
    Call Stack
    # Time Memory Function Location
    1 0.0476 344608 {main}( ) ..test.php:0
    2 2.9793 8389416 file_put_contents ( ) ..test.php:14
    3 2.9796 8390272 mageCoreErrorHandler( ) ..functions.php:0

  • Ok, I ran this script and it works.

    How can I import the file.
    I made an export in Magento 1.4.1 and trying to import in 1.5



  • thanks a lot Benjamin and kamidan,

    I was geting crazy with the subcategories

    have a beautifull day,


  • sivakumar

    i have three store in magento ,when i run this script i got categories from one store only, remaining store categories are not exported.

  • LNS

    thanks alot

  • Ada

    Thanks for the script!

  • Biju

    hi Benjamin, thanks for the script. does it work on 1.7.2? i just tried but returns server error "The website encountered an error while retrieving http://staging.tp.com/categoryids.php. It may be down for maintenance or configured incorrectly." any idea?

    • Biju

      Hi Benjamin, sorry. it was my stupid mistake of not putting the closing php tag as i had just copied and pasted your code from above! thanks a lot. its done. brilliant work!

  • Guinea Pig

    Awesome script. However, with, it has issues. First - it pulls each category name and id into the same cell. Second - it creates each new category in a new column, rather than a row.

    • Muhammad

      Use the following code for 1.6x Magento versions

      getTreeModel ();

      $tree->load ();

      $ids = $tree->getCollection ()->getAllIds ();

      if ($ids) {

      $file = "var/import/catlist.csv";

      file_put_contents($file,"catId, catNamen");

      foreach ( $ids as $id ) {

      $string = $id . ', ' .$category->load($id)->getName() . "n";





      • Guest

        getTreeModel ();

        $tree->load ();

        $ids = $tree->getCollection ()->getAllIds ();

        if ($ids) {

        $file = "var/import/catlist.csv";

        file_put_contents($file,"catId, catNamen");

        foreach ( $ids as $id ) {

        $string = $id . ', ' .$category->load($id)->getName() . "n";





  • Thanks for that...really helpful

  • Chris Sutherland

    Thank you so much for this, It's been really very helpful. I can't believe magento thinks its acceptable not to output category ID's natively! This script has saved me a lot of time.

    I'm using Magento 1.7.02, and Got it to work using Kamidan's version with Sebastijan Placento's fix. Thanks to everyone who made this happen!

  • chris

    $string = $id . ', ' .$category->load($id)->getName() . "/n";

    • tegan_snyder

      or just use PHP_EOL instead of "/n".... that way our Windows friends developing locally work πŸ™‚

      $string = $id . ', ' .$category->load($id)->getName() . PHP_EOL;

  • Vivek Shah

    I want to export only subcategories of a category, how can I do it with above script ?

  • Use following lines for proper formatting-

    (Add "" before "n")

    file_put_contents($file,"catId, catNamen");

    $string = $id . ', ' .$category->load($id)->getName() . "n";


    The script ran just fine that's was cool πŸ™‚

  • No10Count

    Just like the importer - I'm just getting a blank white page.
    Got to be the same reasoning but what?

    • No10Count

      OK got the error finally -
      INVALID HOST REQUEST (domain name)