如何从一个magento安装导出所有属性和属性集,然后导入到另一个安装?


14

我需要从当前网站(Enterprise Edition 1.12.0.0)导出所有产品属性和属性集,并将它们全部导入到新网站(CE 1.8)中。

我经历了这些:

但是我无法弄清楚如何首先导出所有属性,因此我不能花钱进行此过程的任何扩展:(因为我的公司不会提供它。

有人可以指出正确的方向吗?


我经历的所有帖子都集中于从CSV(手动准备)或php脚本中导入属性,而与从源网站中提取属性及其值无关。
2013年

Answers:


27

我这样做是为了从源网站导出所有属性及其选项(如果是下拉属性):

源网站的根目录中的exportAttributes.php :

<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/app/Mage.php';
Mage::app();
$entity_type_id = Mage::getModel('catalog/product')->getResource()->getTypeId();

prepareCollection($entity_type_id);

function prepareCollection($ent_type_id){
    $resource = Mage::getSingleton('core/resource');
    $connection = $resource->getConnection('core_read');
    $select_attribs = $connection->select()
            ->from(array('ea'=>$resource->getTableName('eav/attribute')))
            ->join(array('c_ea'=>$resource->getTableName('catalog/eav_attribute')), 'ea.attribute_id = c_ea.attribute_id');
            // ->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
            // ->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
    $select_prod_attribs = $select_attribs->where('ea.entity_type_id = '.$ent_type_id)
                                            ->order('ea.attribute_id ASC');

    $product_attributes = $connection->fetchAll($select_prod_attribs);

    $select_attrib_option = $select_attribs
                                ->join(array('e_ao'=>$resource->getTableName('eav/attribute_option'), array('option_id')), 'c_ea.attribute_id = e_ao.attribute_id')
                                ->join(array('e_aov'=>$resource->getTableName('eav/attribute_option_value'), array('value')), 'e_ao.option_id = e_aov.option_id and store_id = 0')
                                ->order('e_ao.attribute_id ASC');

    $product_attribute_options = $connection->fetchAll($select_attrib_option);

    $attributesCollection = mergeCollections($product_attributes, $product_attribute_options);
    prepareCsv($attributesCollection);

}

function mergeCollections($product_attributes, $product_attribute_options){

    foreach($product_attributes as $key => $_prodAttrib){
        $values = array();
        $attribId = $_prodAttrib['attribute_id'];
        foreach($product_attribute_options as $pao){
            if($pao['attribute_id'] == $attribId){
                $values[] = $pao['value'];
            }
        }
        if(count($values) > 0){
            $values = implode(";", $values);
            $product_attributes[$key]['_options'] = $values;
        }
        else{
            $product_attributes[$key]['_options'] = "";
        }
        /*
            temp
        */
        $product_attributes[$key]['attribute_code'] = $product_attributes[$key]['attribute_code'];
    }

    return $product_attributes;

}

function prepareCsv($attributesCollection, $filename = "importAttrib.csv", $delimiter = '|', $enclosure = '"'){

    $f = fopen('php://memory', 'w');
    $first = true;
    foreach ($attributesCollection as $line) {
        if($first){
            $titles = array();
            foreach($line as $field => $val){
                $titles[] = $field;
            }
            fputcsv($f, $titles, $delimiter, $enclosure);
            $first = false;
        }
        fputcsv($f, $line, $delimiter, $enclosure); 
    }
    fseek($f, 0);
    header('Content-Type: application/csv');
    header('Content-Disposition: attachement; filename="'.$filename.'"');
    fpassthru($f);
}

这将提供一个csv文件[实际上我使用了“ |” 分开;)]将此csv文件粘贴到目标网站的MAGENTO_ROOT / attribImport目录中,即需要将属性导入到的网站:

现在将以下代码放在目标网站的MAGENTO_ROOT / attribImport **目录中

<?php
define('MAGENTO', realpath(dirname(__FILE__)));
require_once MAGENTO . '/../app/Mage.php';
Mage::app();
// $fileName = MAGENTO . '/var/import/importAttrib.csv';
$fileName = 'importAttrib.csv';
// getCsv($fileName);
getAttributeCsv($fileName);

function getAttributeCsv($fileName){
    // $csv = array_map("str_getcsv", file($fileName,FILE_SKIP_EMPTY_LINES));
    $file = fopen($fileName,"r");
    while(!feof($file)){
        $csv[] = fgetcsv($file, 0, '|');
    }
    $keys = array_shift($csv);
    foreach ($csv as $i=>$row) {
        $csv[$i] = array_combine($keys, $row);
    }
    foreach($csv as $row){
        $labelText = $row['frontend_label'];
        $attributeCode = $row['attribute_code'];
        if($row['_options'] != "")
            $options = explode(";", $row['_options']); // add this to createAttribute parameters and call "addAttributeValue" function.
        else
            $options = -1;
        if($row['apply_to'] != "")
            $productTypes = explode(",", $row['apply_to']);
        else
            $productTypes = -1;
        unset($row['frontend_label'], $row['attribute_code'], $row['_options'], $row['apply_to'], $row['attribute_id'], $row['entity_type_id'], $row['search_weight']);
        createAttribute($labelText, $attributeCode, $row, $productTypes, -1, $options);
    }
}


/**
 * Create an attribute.
 *
 * For reference, see Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().
 *
 * @return int|false
 */
function createAttribute($labelText, $attributeCode, $values = -1, $productTypes = -1, $setInfo = -1, $options = -1)
{

    $labelText = trim($labelText);
    $attributeCode = trim($attributeCode);

    if($labelText == '' || $attributeCode == '')
    {
        echo "Can't import the attribute with an empty label or code.  LABEL= [$labelText]  CODE= [$attributeCode]"."<br/>";
        return false;
    }

    if($values === -1)
        $values = array();

    if($productTypes === -1)
        $productTypes = array();

    if($setInfo !== -1 && (isset($setInfo['SetID']) == false || isset($setInfo['GroupID']) == false))
    {
        echo "Please provide both the set-ID and the group-ID of the attribute-set if you'd like to subscribe to one."."<br/>";
        return false;
    }

    echo "Creating attribute [$labelText] with code [$attributeCode]."."<br/>";

    //>>>> Build the data structure that will define the attribute. See
    //     Mage_Adminhtml_Catalog_Product_AttributeController::saveAction().

    $data = array(
                    'is_global'                     => '0',
                    'frontend_input'                => 'text',
                    'default_value_text'            => '',
                    'default_value_yesno'           => '0',
                    'default_value_date'            => '',
                    'default_value_textarea'        => '',
                    'is_unique'                     => '0',
                    'is_required'                   => '0',
                    'frontend_class'                => '',
                    'is_searchable'                 => '1',
                    'is_visible_in_advanced_search' => '1',
                    'is_comparable'                 => '1',
                    'is_used_for_promo_rules'       => '0',
                    'is_html_allowed_on_front'      => '1',
                    'is_visible_on_front'           => '0',
                    'used_in_product_listing'       => '0',
                    'used_for_sort_by'              => '0',
                    'is_configurable'               => '0',
                    'is_filterable'                 => '0',
                    'is_filterable_in_search'       => '0',
                    'backend_type'                  => 'varchar',
                    'default_value'                 => '',
                    'is_user_defined'               => '0',
                    'is_visible'                    => '1',
                    'is_used_for_price_rules'       => '0',
                    'position'                      => '0',
                    'is_wysiwyg_enabled'            => '0',
                    'backend_model'                 => '',
                    'attribute_model'               => '',
                    'backend_table'                 => '',
                    'frontend_model'                => '',
                    'source_model'                  => '',
                    'note'                          => '',
                    'frontend_input_renderer'       => '',                      
                );

    // Now, overlay the incoming values on to the defaults.
    foreach($values as $key => $newValue)
        if(isset($data[$key]) == false)
        {
            echo "Attribute feature [$key] is not valid."."<br/>";
            return false;
        }

        else
            $data[$key] = $newValue;

    // Valid product types: simple, grouped, configurable, virtual, bundle, downloadable, giftcard
    $data['apply_to']       = $productTypes;
    $data['attribute_code'] = $attributeCode;
    $data['frontend_label'] = array(
                                        0 => $labelText,
                                        1 => '',
                                        3 => '',
                                        2 => '',
                                        4 => '',
                                    );

    //<<<<

    //>>>> Build the model.

    $model = Mage::getModel('catalog/resource_eav_attribute');

    $model->addData($data);

    if($setInfo !== -1)
    {
        $model->setAttributeSetId($setInfo['SetID']);
        $model->setAttributeGroupId($setInfo['GroupID']);
    }

    $entityTypeID = Mage::getModel('eav/entity')->setType('catalog_product')->getTypeId();
    $model->setEntityTypeId($entityTypeID);

    $model->setIsUserDefined(1);

    //<<<<

    // Save.

    try
    {
        $model->save();
    }
    catch(Exception $ex)
    {
        echo "Attribute [$labelText] could not be saved: " . $ex->getMessage()."<br/>";
        return false;
    }

    if(is_array($options)){
        foreach($options as $_opt){
            addAttributeValue($attributeCode, $_opt);
        }
    }

    $id = $model->getId();

    echo "Attribute [$labelText] has been saved as ID ($id).<br/>";

    // return $id;
}

function addAttributeValue($arg_attribute, $arg_value)
{
    $attribute_model        = Mage::getModel('eav/entity_attribute');

    $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
    $attribute              = $attribute_model->load($attribute_code);

    if(!attributeValueExists($arg_attribute, $arg_value))
    {
        $value['option'] = array($arg_value,$arg_value);
        $result = array('value' => $value);
        $attribute->setData('option',$result);
        $attribute->save();
    }

    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
    $attribute_table        = $attribute_options_model->setAttribute($attribute);
    $options                = $attribute_options_model->getAllOptions(false);

    foreach($options as $option)
    {
        if ($option['label'] == $arg_value)
        {
            return $option['value'];
        }
    }
   return false;
}
function attributeValueExists($arg_attribute, $arg_value)
{
    $attribute_model        = Mage::getModel('eav/entity_attribute');
    $attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;

    $attribute_code         = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
    $attribute              = $attribute_model->load($attribute_code);

    $attribute_table        = $attribute_options_model->setAttribute($attribute);
    $options                = $attribute_options_model->getAllOptions(false);

    foreach($options as $option)
    {
        if ($option['label'] == $arg_value)
        {
            return $option['value'];
        }
    }

    return false;
}

注意:尽管已处理了所有异常,但是为了安全起见,请在导入这些属性之前备份数据库。进口愉快!

谢谢 :


1
'test'.从导出脚本的第54行中删除,导出运行正常。
Jaap Haagmans 2014年

哎呀!我已经删除了“测试” :)
Shathish

导入脚本导致500服务器错误。
加布里埃莱2015年

我已经将csv文件和importAttribute.php文件放置在我的magento安装的/ var / import目录中,但是出现403 Forbidden错误。
加布里埃莱2015年

有什么办法导出属性集?
Haim

1

我认为最简单的方法就是拿走所有桌子并将它们复制过来。

根据您是否关心其他属性(客户,地址,订单等),您可以复制所有内容,也可以选择产品属性并将其插入新数据库。

选中eav_entity_type,通常catalog_product为ID 4。

然后复制一切从eav_attribute,并catalog_eav_attributeentity_type_id = 4你新的实例。注意不要破坏外键。

如果您也要复制产品,这是一个问题,因为属性的ID可能会更改!

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.