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:

<?php
 
	define('MAGENTO', realpath(dirname(__FILE__)));
	require_once MAGENTO . '/app/Mage.php';
	Mage::app();
 
	$category = Mage::getModel ( 'catalog/category' );
	$tree = $category->getTreeModel ();
	$tree->load ();
 
	$ids = $tree->getCollection ()->getAllIds ();
 
	if ($ids) {
		$file = "var/import/catwithid.csv";
		file_put_contents($file,"catId, catName\n");
		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!

This entry was posted in Knowledge Base, Magento and tagged , , , , , , , . Bookmark the permalink.

37 Responses to Quick script to export Magento categories with IDs


  1. Moshe

    thank you this worked great

    Reply


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

    Reply


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

      Reply


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

    Reply


  4. 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!

    Reply


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

      getTreeModel();
      $tree->load();
      $ids = $tree->getCollection()->getAllIds();
      if ($ids) {
      $file = "var/import/catwithid.csv";
      file_put_contents($file, "catId,catName,catParent_id,catLevel\n");//two more fields
      foreach ($ids as $id) {
      // ADDED BY Pragnesh Karia starts
      $pk = Mage::getModel('catalog/category');
      $pk->load($id);
      $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);
      }
      }
      ?>

      Reply


  5. Thanks !!!

    That worked perfectly.

    Reply



  6. Finees

    Awesome! Now, only if it was this easy to import the categories back into Magento… life would be better :-)

    Reply


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

      Reply


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

    Reply


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

      Reply


  8. 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~

    Reply


  9. 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 1.5.0.1

    Reply


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

      Reply


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

        Thanks!

        Reply


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

          Reply


  10. Thanks, this helped me out!

    Reply


  11. 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?!

    Reply


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

      Reply


  12. 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";

    Reply



  13. Jerick

    Salamat!!!

    Reply


  14. Thanks!! Saved a ton of time.

    Reply



  15. mjamb

    thx…works great on 1.5.1

    Reply


  16. Thanks It Helped me a lot!

    Reply


  17. 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';
    Mage::app();

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

    $nodes = $tree->getNodes();

    if ($nodes) {
    $file = "var/import/cats.csv";
    file_put_contents($file,"\"catId\",\"catName\",\"catPath\"\n");
    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";
    file_put_contents($file,$string,FILE_APPEND);
    echo "$string\n";
    }
    }

    Reply


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

    Reply


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

      Reply



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

    Name;Url;Sku;Manufacturer;Ean;categories

    How i do that export?

    Thanks!

    Reply


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

      Reply


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

    thx

    Reply



  21. 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:\xampp\htdocs\tigopromos\tpromos\home\tpromos\public_html\var\test.php on line 14′ in E:\xampp\htdocs\tigopromos\tpromos\home\tpromos\public_html\app\code\core\Mage\Core\functions.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:\xampp\htdocs\tigopromos\tpromos\home\tpromos\public_html\var\test.php on line 14 in E:\xampp\htdocs\tigopromos\tpromos\home\tpromos\public_html\app\code\core\Mage\Core\functions.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

    Reply


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

    Br,

    Steve

    Reply


  23. thanks a lot Benjamin and kamidan,

    I was geting crazy with the subcategories

    have a beautifull day,

    eduardo

    Reply


Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">