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 🙂