Magento export categories with id

A friend asked me to help out import some products and categories from an old database to a brand new magento install. What I first did was to construct a CSV file with all the categories from the old store (that was the easy part…) and import them to magento. I followed this thread and the import when smooth. Now I needed to get the ids that magento addigned to my categories so that I could import a product inside the categories so that my friend won’t have to do it in backend.

First thing I did was to look on magento forums how to get all store categories. After finding this great thread, i came up with this little script which I put into my template folder in /catalog/allcategories.phtml:

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

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

if ($ids) {
$fp = fopen('var/import/catwithid.csv', 'a');
fwrite($fp,  'catId, catName\n');
foreach ( $ids as $id ) {
                $string = $id . ', ' .$category->load($id)->getName() . '\n';
fwrite($fp,  $string);
}
fclose($fp);
}

As a note, you need to make sure that /var/import/catwithid.csv exists and it’s writeable by your web server. You can make sure it is by chmod-ing it to 777

touch var/import/catwithid.csv # we create the file
chmod 777 var/import/catwithid.csv #make sure it's writeable

Since this was a dev install, I then just loaded that script into a block element by editing the Home Page inside the CMS section:

{{block type="core/template" template="catalog/allcategories.phtml"}}

Hope this helps someone 🙂

5 thoughts on “Magento export categories with id”

  1. very good article helped me to get all categories but how can i upload these categories to online store
    is any method i can use to upload this csv file and get data from this csv file or i need to copy it manually.
    suggest me something good
    thanks

  2. +1 how may I import the categories ? If I can’t import them, it’s useless to export them.

    Also, your script does not keep sub-categories : even if we are able to import them, we’ll must reorder them. If you’ve got 20 categories, it’s OK but if it’s more…

Leave a Reply

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