We often need to automate the creation of our Magento categories. This can be useful when you change the environment or after a complete reinstall. Here is a small script that allows you to create your category structure by importing a CSV file from the command line.
Installation
Script is available on GitHub : https://github.com/jreinke/magento-import-categories.
- Download script here
- Copy the downloaded file into Magento
shell/
folder
Usage
cd /path/to/magento php shell/import_categories.php -- -f data/categories.csv |
In our example, CSV file is located in data/categories.csv
.
And it looks like this:
Furniture | ||
Living Room | ||
Bedroom | ||
Electronics | ||
Cell Phones | ||
Cameras | ||
Accessories | ||
Digital Cameras | ||
Computers | ||
Laptops | ||
Hard Drives | ||
RAM / Memory | ||
Apparel | ||
Shirts | ||
Shoes | ||
Men | ||
Women | ||
Music | ||
Ebooks |
To automatically translate the categories for another store view, you must add a row header and column as shown below:
store_fr | |||
Furniture | Meubles | ||
Living Room | Salon | ||
Bedroom | Chambre à coucher | ||
Electronics | Electronique | ||
Cell Phones | Téléphones portables | ||
Cameras | Appareils photo | ||
Accessories | Accessoires | ||
Digital Cameras | Appareils photo numériques | ||
Computers | Ordinateurs | ||
Laptops | Ordinateurs portables | ||
Hard Drives | Disques Durs | ||
RAM / Memory | Mémoire RAM | ||
Apparel | Vêtements | ||
Shirts | Chemises | ||
Shoes | Chaussures | ||
Men | Hommes | ||
Women | Femmes | ||
Music | Musique | ||
Ebooks | Livres numériques |
If category tree is not empty, use --force
option to delete old categories automatically:
php shell/import_categories.php -- -f data/categories.csv --force |
Finally, you can specify a custom delimiter or enclosure. By default, they are those of fgetcsv
function of PHP. For more information, see help:
php shell/import_categories.php help |
52 Responses to “Magento: Import categories from cli”
It will be great if you can provide a script to create the csv
I need a sample csv too, did you get it from Johann?
Excellentissime.
Pour des problématiques d’accents j’ai du modifier la ligne 37:
‘name’ => utf8_encode(trim($name)),
Merci pour ce petit script fort utile.
Merci !
Le utf8_encode ne devrait pas être nécessaire si le fichier CSV est lui aussi en utf8.
Hi,
Really nice work! Just to clarify: the field separator in categories.csv is a tab in this example?
Thanks,
Mark
Thank you.
In the example, field separator is comma.
Nice post. it works great for me
Can use CSV Easy or CSVed
Ciao, ho usato il tuo script, l’ho stesso in modo di poter fare anche l’esportazione delle categorie e la generazione del file csv, diretamente da shell, ora mi servono gli attributi, i set e i prodotti. In tanto se vuoi posso rilascirti la nuova classe Export, ispirata alla tua Import, e la nuova classe Import stessa da me.
Vuoi che lo metto su ghithub?
Non saprei come fare, questa sarebbe la mia prima volta. XD
Comunque alla Classe Import stessa ho messo i tuoi riconoscimenti in coda, come creatore e i mei come svilupatore delle funzionalità stessa. E alla nuova Export, ti ho messo come ispirazione.
—————————————
Translate = http://goo.gl/c799a
Works like a charm, excellent work thanks!
Thanks for the script.
1- What is abstract.php mentioned in the file? I don’t see abstract.php in your package
2- Does the script write directly to MySQL? if yes, where are the credentials defined?
thanks
Hey!
>>1- What is abstract.php mentioned in the file? I don’t see abstract.php in your package
It’s magento shell abstract class(used for php files that will be used in cli)
>>2- Does the script write directly to MySQL? if yes, where are the credentials defined?
As I see it works with magento models… so no directly access to mysql.
abstract.php is for Mage_Shell_Abstract class.
Credentials are those defined for Magento, in local.xml
Is there a similar script for importing products?
Thanks
Magento already has a product import feature from csv file.
Is it possible to modify the script to automatically make child categories anchors?
Or to import additional category information such as description and metatags?
Thank you so much for this script. So simple. So powerful. A real life saver for transferring categories over form a large site to Magento.
I’m having issues running the PHP script in XAMPP even though I added the path to php in the .profile file. When I run the script from the Terminal, it just prints out the code from the .php page to the Terminal.
Merci, super script qui m’a fait gagner pas mal de temps
I have attempted to run the script from the SQL and the terminal (Website is currently hosted locally using MAMP) and I receive the following error, any idea where I’ve gone wrong?
Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[HY000] [2002] No such file or directory’ in /Applications/MAMP/htdocs/magento/lib/Zend/Db/Adapter/Pdo/Abstract.php:129
Stack trace:
#0 /Applications/MAMP/htdocs/magento/lib/Zend/Db/Adapter/Pdo/Abstract.php(129): PDO->__construct(‘mysql:host=loca…’, ‘toms’, ‘password’, Array)
#1 /Applications/MAMP/htdocs/magento/lib/Zend/Db/Adapter/Pdo/Mysql.php(96): Zend_Db_Adapter_Pdo_Abstract->_connect()
#2 /Applications/MAMP/htdocs/magento/lib/Varien/Db/Adapter/Pdo/Mysql.php(313): Zend_Db_Adapter_Pdo_Mysql->_connect()
#3 /Applications/MAMP/htdocs/magento/lib/Zend/Db/Adapter/Abstract.php(459): Varien_Db_Adapter_Pdo_Mysql->_connect()
#4 /Applications/MAMP/htdocs/magento/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query(‘SET NAMES utf8′, Array)
#5 /Applications/MAMP/htdocs/magento/lib/Varien/Db/Adapter/Pdo/Mysql.php(419): Zend_Db_Adapter_Pdo_Abstract->query(‘SET NAMES utf8′, Array)
#6 /Applications/MAMP/htdocs/magento/app/code/core/Mage/Core/M in /Applications/MAMP/htdocs/magento/lib/Zend/Db/Adapter/Pdo/Abstract.php on line 144
Hi can you provide csv to upload ? an geting error on my local machine
C’est top
Merci pour ce bon script.
Script is working well, all categories got inserted correctly. But is there a way to set all categories as anchor? I tried to put the ‘is-anchor’ to 1 in the file.
When i ran the code again the ‘is_anchor’ was still 0 + the name and active state were 0 too..
Is there a way to set them to anchor true?
Thx Tom
I manually deleted all categories. After this (and ofcourse without the -force command) everything imported as it should. All categories are anchors now.
That is an awesome script! Thanks for that!
Hi,
I have this error when try to execute ?!
Parse error: syntax error, unexpected T_STRING, expecting T_OLD_FUNCTION or T_FUNCTION or T_VAR or ‘}’ in /homepages/5/d295630334/htdocs/demo.webclik.tn/ fc-magento/shell/import_categories.php on line 19
Work as charm, Require PHP CLi 5.2 or more.
Thank you.
How to set description and images for categories and subcategories via csv file
You’re a gentleman and a scholar. Thanks!
Hi,
I am using the script and it’s fantastic.
it’s possibile change the script so that i can also add categories without deleting the old?
I’m not a expert in php
Thank you,
Gianny.
Hi, I love the script by the way. I am writing because I used the upload, but the way I had my code written, it did not get all the categories loaded. Then when I was going to reload, the person setting up the navigation was freaking out because he did it according to a setting in the categories. I added the new categories manually and even though that is more work, it is fine. My problem is, if later on we want to add more categories through an upload like this, are we able to append what we already have if we don’t use force? I am scared to mess with it because I am not doing the php stuff and I do not want to make more work for someone else.
Thanks,
Tracy
MITICO!!!!
Grazie, funziona perfettamente!
hi..
can we specify category id in the csv?
can we have a sample of teh categories.csv.?
Nice post. I used to be checking continuously this weblog and I’m impressed! Extremely useful information particularly the final phase
I deal with such information much. I was seeking this certain information for a very long time. Thanks and good luck.
Very Usefull ,,
Thank you Johann Reinke.
Thank you for your script, is there a possibility to add a translation?
Bonjour
Merci tout d’abord pour ce travail !
Ce script a toujours très bien fonctionné, mais depuis que j’ai voulu l’utiliser sur un site de test chez 1and1 avec la dernière version de magento 1.9.1
j’ai l’erreur suivante :
X-Powered-By: PHP/5.2.17
Content-type: text/html
Parse error: syntax error, unexpected T_FUNCTION in /homepages/33/d406159463/htdocs/LB/app/code/core/Mage/Core/Helper/Abstract.php on line 240
une idée
salutation :=)
Max
Bonjour,
je suis un debutant, svp m’aider.
je ne sais pas où il faut mettre ce script
php shell/import_categories.php — -f data/categories.csv
et comment l’executer
stl
juste te laissé un thank pour ce post
chez moi ça fonctionne a merveille
Coullll.. et du courage
Franck (DEV WEB )
désolé pour mon retour,
j’était entrain de réfléchir sur la problématique suivante:
Dans le cas d’un site multi store et pour compliqué multi boutique, comment devrais-je structurer mon fichier csv pour assurer l’import ou bien et comment faire un update du script d’import???
j’avoue que je ne vois pas bien vers ou commencé
Merci de bien vouloir te penché sur ma problématique.
Hi,
is ist possible to modify the script to add root categories with subcategories?
got it, the ugly way: changed line 143
from
$rootId = Mage::app()->getDefaultStoreView()->getRootCategoryId();
to
$rootId = [My Root Category ID];
its not the best way, but if you don’t have dozens of root categories, you can handle it this way and just run the script 1, 2 or 3 times.
maybe somebody is able to provide a solution where you can add the roots to the csv file.
Addition:
Have to comment out line 128 to 137.
Otherwise it won’t run the second or third time.
not beautiful, but a basic solution.
How we can import categories in multi website environment.
Thanks
awesome script !!!!! please add to this script you are obviously talented enough .
add such things as meta description, page title,is anchor ect into csv coumns
Thanks regardless
Hi! This is very helpful! Do you have sample csv to import? and.. can we add the category ids too? and not just automatic increment? Thanks
How to do the same task in magento 2.
Thanks for sharing this script, I just looking for category import tools for new built sites. It would be better if could export meta info of categories. Anyway, thank you!
Nice work.
I only have one question regarding the CSV structure.
As far as i can understand I have to put my main category-tree on the left, but in the backend you can see the “website” as “top” category, but it doesn´t seem that you are putting this top-level category in your CSV. How is this handled here ? Do I have to “ignore” this top-category and doesn´t that mean multi-store environment is not supported ?
Thanks for any help!
Hi,
I ran the script, and it told me categories were already existing (although it was not the case) and i had to run –force
I ran the script with –force, and it correctly inserted my categories but… deleted all the others..
What did i do wrong ? ( i didn’t specify in the file any store or website, as i have only one website/store) …
Thanks
salut Johann Reinke
s’il vous plait indique moi ou je dois place le fichier categoris.csv
car j ai pas trouver le repertoir “data”