Search code examples
drupaldrupal-commercecsv-importdrupal-feeds

Import multi-sized product with single SKU


I have regular Drupal Commerce setup with installed Feeds, Feeds Tamper and Commerce Feeds modules. Here is tiny piece of the CSV file I'm trying to import:

SKU,Title,Price,Sizes,Model
JKR122/1,Red T-Shirt,44,"42,44,46",JKR122
JKR122/2,Blue T-Shirt,44,"42,44,46",JKR122

Is it possible using Feeds Tamper, to explode "Sizes" column and import each as separate product. Probably it will be needed to append exploded size to SKU.

I'm no pro in Excel, so if it is possible to easily reformat this huge CSV file, please tell me how.


Solution

  • As problem had to be solved today, I wrote PHP-script which reformats my CSV:

    I'll leave question opened, in case anuone knows if this can be done by "Drupal-way".

    <?php
    
    define('ATTR_SIZE', 'Sizes');
    define('ATTR_SKU', 'SKU');
    define('IMPORT_FILE', 'import_file.csv');
    define('EXPORT_FILE', 'export_file.csv');
    define('CSV_DELIMITER', ',');
    
    // Open csv
    if(!file_exists(IMPORT_FILE) || !is_readable(IMPORT_FILE))
      die('Check file');
    
    $header = NULL;
    $all_rows = array();
    
    if (($handle = fopen(IMPORT_FILE, 'r')) !== FALSE) {
      while (($row = fgetcsv($handle, 1000, CSV_DELIMITER)) !== FALSE) {
        if (!$header)
          $header = $row;
        else
          $all_rows[] = array_combine($header, $row);
      }
      fclose($handle);
    }
    
    // Process csv
    $new_rows = array();
    
    foreach ($all_rows as $key => $row) {
      if (!empty($row[ATTR_SIZE])) {
        $original_row = $row;
        $sizes = explode(',', $row[ATTR_SIZE]);
    
        foreach ($sizes as $size) {
          $trimmed_size = trim($size);
    
          if (!empty($trimmed_size)) {
            $row = $original_row;
            $row[ATTR_SIZE] = $trimmed_size; // Save size
            $row[ATTR_SKU] = $row[ATTR_SKU] . '/' . $trimmed_size; // Modify SKU
            $new_rows[] = $row; // Add new row
          }
        }
      }
      else {
        $new_rows[] = $row;
      }
    }
    
    // Save csv
    $header = NULL;
    $handle = fopen(EXPORT_FILE, 'w');
    
    foreach ($new_rows as $fields) {
      if (!$header) {
        fputcsv($handle, array_keys($fields));
        $header = TRUE;
      }
      fputcsv($handle, $fields);
    }
    fclose($handle);