So, what I need to do is to convert the contents of a .pot file to an array.

I know there is _locale_import_read_po(), but when I tried using it with the following code, I got an error.

$translations = _locale_import_read_po('db-store', 'translations.pot');

The translations.pot file is located in the same directory containing the file with the code I wrote.

The error I get with dpm($translations) is the following one.

Error message

The translation import failed, because the file could not be read.

This is the code from the _locale_import_read_po() function, that outputs that error.

// The file will get closed by PHP on returning from this function.
$fd = fopen($file->uri, 'rb');
if (!$fd) {
  _locale_import_message('The translation import failed, because the file %filename could not be read.', $file);
  return FALSE;

As far as I know the 'rb' file open mode is to open non-text files.

Why do I get that error message?


The second parameter of _locale_import_read_po() is a Drupal file object, which in Drupal 7 is simply a stdClass object.

The quicker way to use that function and pass a file object as it expects is using code similar to the following one.

 $po_files = file_scan_directory('./', '^translation\.po$', array('recurse' => FALSE));
 if (count($po_files)) {
   require_once DRUPAL_ROOT . '/includes/locale.inc';
   $po_file = reset($po_files);
   _locale_import_read_po('db-store', $po_file);

Notice that the second argument of file_scan_directory() is a preg_match() regular expression, not a filename.

Using that code, you don't need to save the file using the file API, which is essentially useless, since there is already a file in the file system.
file_save() stores the file in the database; for a file that is used for a single operation like that, it's not necessary.

I used st() as example for writing the code I shown in this answer.

You could also make the code I show more generic to accept a regular expression and a directory name, and use it to load more files.

function mymodule_import_translations($directory, $pattern) {
  $po_files = file_scan_directory($directory, $pattern, array('recurse' => FALSE));
  if (count($po_files)) {
    require_once DRUPAL_ROOT . '/includes/locale.inc';
    foreach ($po_files as $po_file) {
      _locale_import_read_po('db-store', $po_file);

The $file parameter needs to be a Drupal file object corresponding to the PO file to import.

You can create one using the file_save function:

$file = file_save((object)array(
    'filename' => $file_name,
    'uri' => $destination_uri,
    'status' => FILE_STATUS_PERMANENT,
    'filemime' => file_get_mimetype($destination_uri),

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy