Magento : Importer des catégories en ligne de commande

On a souvent besoin d’automatiser la création de catégories sur nos instances Magento. Cela peut être utile quand on change d’environnement ou bien après une réinstallation complète. Voici un petit script qui vous permettra de créer votre arborescence de catégories en important un fichier CSV en ligne de commande.


Le script est disponible sur GitHub :

  1. Téléchargez le script ici
  2. Copiez le fichier dans le répertoire shell/ de Magento


cd /path/to/magento
php shell/import_categories.php -- -f data/categories.csv

Dans notre exemple, on a placé le fichier CSV à importer dans data/categories.csv.

Et le fichier CSV ressemble à ceci :

Living Room
Cell Phones
Digital Cameras
Hard Drives
RAM / Memory

Pour traduire automatiquement les catégories pour une autre vue magasin, il faut ajouter une ligne d’en-tête et une colonne comme ci-dessous :

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

Si des catégories existent déjà, utilisez l’option --force pour les supprimer automatiquement :

php shell/import_categories.php -- -f data/categories.csv --force

Enfin, vous pouvez spécifier un séparateur et un caractère d’encadrement personnalisés. Par défaut, ce sont ceux de la fonction fgetcsv de PHP. Pour plus d’informations, consultez l’aide :

php shell/import_categories.php help

52 réponses à “Magento : Importer des catégories en ligne de commande”

  1. wonderland dit :

    It will be great if you can provide a script to create the csv :)

  2. baoutch dit :

    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.

  3. Mark dit :


    Really nice work! Just to clarify: the field separator in categories.csv is a tab in this example?



  4. Nice post. it works great for me

  5. camulatz dit :

    Can use CSV Easy or CSVed

  6. Victor D. dit :

    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 =

  7. Cor-Paul dit :

    Works like a charm, excellent work thanks!

  8. Syd dit :

    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?


    • Alex dit :

      >>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.

    • Johann Reinke dit :

      abstract.php is for Mage_Shell_Abstract class.
      Credentials are those defined for Magento, in local.xml

  9. Syd dit :

    Is there a similar script for importing products?


  10. Jim dit :

    Is it possible to modify the script to automatically make child categories anchors?

  11. Lloyd dit :

    Or to import additional category information such as description and metatags?

  12. Adam dit :

    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.

  13. Edward dit :

    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.

  14. Nicolas dit :

    Merci, super script qui m’a fait gagner pas mal de temps :)

  15. Tom Sinclair dit :

    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

  16. Mounish dit :

    Hi can you provide csv to upload ? an geting error on my local machine

  17. Hassan LAAREJ dit :

    C’est top :)
    Merci pour ce bon script.

  18. Tom VLDK dit :

    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

    • Tom VLDK dit :

      I manually deleted all categories. After this (and ofcourse without the -force command) everything imported as it should. All categories are anchors now.

  19. Greg Robbins dit :

    That is an awesome script! Thanks for that!

  20. Krimos dit :

    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/ fc-magento/shell/import_categories.php on line 19

  21. Krimos dit :

    Work as charm, Require PHP CLi 5.2 or more.
    Thank you.

  22. Payas dit :

    How to set description and images for categories and subcategories via csv file

  23. Shawn Hood dit :

    You’re a gentleman and a scholar. Thanks!

  24. Gianny dit :

    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,

  25. TracyLee dit :

    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.

  26. silvia dit :

    Grazie, funziona perfettamente!

  27. Youshrin dit :

    can we specify category id in the csv?

    can we have a sample of teh categories.csv.?

  28. 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.

  29. Manish Patel dit :

    Very Usefull ,,

    Thank you Johann Reinke.

  30. Iuli dit :

    Thank you for your script, is there a possibility to add a translation?

  31. Max dit :


    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 :=)

  32. ABDELMAJID dit :

    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

  33. franck dit :

    juste te laissé un thank pour ce post
    chez moi ça fonctionne a merveille

    Coullll.. et du courage

    Franck (DEV WEB )

  34. franck dit :

    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.

  35. Hi,

    is ist possible to modify the script to add root categories with subcategories?

    • got it, the ugly way: changed line 143

      $rootId = Mage::app()->getDefaultStoreView()->getRootCategoryId();

      $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.

  36. Manoj dit :

    How we can import categories in multi website environment.


  37. Snowjockey dit :

    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

  38. Reazer dit :

    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

  39. pauli dit :

    How to do the same task in magento 2.

  40. bill dit :

    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!

  41. JS dit :

    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!

  42. fred dit :

    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) …

  43. jalal hab dit :

    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 »

Laisser un commentaire

* Champs requis