HummingbirdUK main logo

Coding solutions to business problems

About us

We use code to create solutions to business challenges, bottle-necks and headaches.

If you think your business has a problem that can be solved through code, we are happy to chat things through without any obligation.

Get in touch

Export Magento categories and IDs to CSV

Home / Blog / Export Magento categories and IDs to CSV

Written by Giles Bennett

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.

require_once 'app/Mage.php';
$allCategories = Mage::getModel ( 'catalog/category' );
$categoryTree = $allCategories->getTreeModel();
$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 :


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.

Author : Giles Bennett

About the author

Giles Bennett built his first website in 1996, and is old enough to miss Netscape Navigator. Initially a lawyer, he jumped ship to IT in 2008, and after 5 years as a freelancer, he founded HummingbirdUK in 2013. He can be reached by email at