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.