Generate magento translation file

Generate Magento translation CSV file

We know that Magento provides great feature for translation of text strings in code. Such content that needs to be localized for different store views is outputted through  __()  helper function. It will search for data loaded from locale translation  .csv  file and if found match for current store view it will be replaced with it.

So in process of developing Magento theme or extension developer needs to add all such text strings into  .csv  translation file. In some cases it could be very big list, like about 300-600 entries. To not do this monkey job manually lets try to automate it.

Here is the plan. Script will iterate through all yours code files, find all calls to  __()  helper translation function and save them into locale  .csv  file.

Of cause we can write old school recursive function to get all files in specified directory and subdirectories, but lets use more cool modern SPL Recursive Directory Iterator.

This will iterate files starting with  $sourcePath  directory. We don’t need to scan all the files, just code once, so lets skip non code files to make it work faster:

Were $searchExtensions is array of file extensions we need to look into, in our case it is  .php  and .phtml . Next we read file contents and get all entries of translation function use with regular expression.

You can see  $strTranslateFunc  string variable in our expression. It should have name of translation function, we set it here to '->__' , but it can be changed to something else, for example if you need to get calls to translate function from specific helper. Now  preg_match_all()  function will save results of matches in  $arrMatches  array. Lets iterate through it to save unique entries to resulting array.

Note that we trim entries from quotes and translate function name, as our expression returns them in matches. And finally when we have all unique texts to localize in  $arrItems[]  lets save them to  .csv  file.

And now lets get it all together.

Feel free to use this code to generate translation locale .csv files for your Magento themes and extensions to save your time and enjoy programming.

Leave a Reply

Your email address will not be published. Required fields are marked *