【问题标题】:CSV Import/Export problems in MagentoMagento 中的 CSV 导入/导出问题
【发布时间】:2015-12-10 23:04:48
【问题描述】:

好的,所以我设法按照 justcode.in 上的一组说明将我的类别导出到 csv 文件中。我想将我的 CSV 导入新安装的 Magento。

我正在运行 Magento 1.9.2.2 当我尝试运行配置文件时,它会找到我的 CSV 文件并加载它,但它会抛出此错误。

错误信息,

<br /> <b>Fatal error</b>: Call to undefined method ImpCat_Catalog_Model_Convert_Adapter_Category::getStoreById() in <b>/var/www/public/secondstore/app/code/local/ImpCat/Catalog/Model/Convert/Adapter/Category.php</b> on line <b>32</b><br />

CSV文件的结构就是这件事,

store;categories;is_active;meta_title;meta_keywords;meta_description;include_in_menu;is_anchor;description

然后我在 app\code\local\ImpCat\Catalog\etc\config.xml 创建了 config.xml。 这个文件看起来像这样,

<?xml version="1.0"?>
<config>
 <global>
  <models>
   <catalog>
    <rewrite>
     <convert_adapter_category>ImpCat_Catalog_Model_Convert_Adapter_Category</convert_adapter_category>
    </rewrite>
   </catalog>
  </models>
 </global>
</config>

然后我继续在 app\code\local\ImpCat\Catalog\Model\Convert\Adapter\Category.php 中创建 Category.php

Category.php 长这样,

<?php
class ImpCat_Catalog_Model_Convert_Adapter_Category extends Mage_Eav_Model_Convert_Adapter_Entity
{
 protected $_categoryCache = array();
 protected $_stores;
 /**
 * Category display modes
 */
 protected $_displayModes = array( 'PRODUCTS', 'PAGE', 'PRODUCTS_AND_PAGE');

 public function parse()
 {
 $batchModel = Mage::getSingleton('dataflow/batch');
 $batchImportModel = $batchModel->getBatchImportModel();
 $importIds = $batchImportModel->getIdCollection();
 foreach ($importIds as $importId){
  $batchImportModel->load($importId);
  $importData = $batchImportModel->getBatchData();
  $this->saveRow($importData);
 }
 }
 /**
 * Save category (import)
 * @param array $importData
 * @throws Mage_Core_Exception
 * @return bool
 */
 public function saveRow(array $importData)
 {
 if (empty($importData['store'])) {
   if (!is_null($this->getBatchParams('store'))) {
   $store = $this->getStoreById($this->getBatchParams('store'));
   } else {
   $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store');
   Mage::throwException($message);
   }
 }else{
  $store = $this->getStoreByCode($importData['store']);
 }
 if ($store === false){
  $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']);
  Mage::throwException($message);
 }
 $rootId = $store->getRootCategoryId();
  if (!$rootId) {
  return array();
  }
 $rootPath = '1/'.$rootId;
  if (empty($this->_categoryCache[$store->getId()])) {
  $collection = Mage::getModel('catalog/category')->getCollection()
              ->setStore($store)
              ->addAttributeToSelect('name');
 $collection->getSelect()->where("path like '".$rootPath."/%'");
 foreach ($collection as $cat) {
  $pathArr = explode('/', $cat->getPath());
  $namePath = '';
  for ($i=2, $l=sizeof($pathArr); $i<$l; $i++) {
  $name = $collection->getItemById($pathArr[$i])->getName();
  $namePath .= (empty($namePath) ? '' : '/').trim($name);
  }
  $cat->setNamePath($namePath);
 }
  $cache = array();
  foreach ($collection as $cat) {
  $cache[strtolower($cat->getNamePath())] = $cat;
  $cat->unsNamePath();
  }
  $this->_categoryCache[$store->getId()] = $cache;
  }
  $cache =& $this->_categoryCache[$store->getId()];
  $importData['categories'] = preg_replace('#\s*/\s*#', '/', trim($importData['categories']));
  if (!empty($cache[$importData['categories']])) {
  return true;
  }
  $path = $rootPath;
  $namePath = '';
  $i = 1;
 $categories = explode('/', $importData['categories']);
 /*$IsActive = $importData['IsActive'];*/
 $IsActive = $importData['is_active'];
 $IsAnchor =$importData['is_anchor'];
 $Description =$importData['description'];
 $IncludeInMenu=$importData['include_in_menu'];
 $MetaTitle=$importData['meta_title'];
 $MetaKeywords=$importData['meta_keywords'];
 $MetaDescription=$importData['meta_description'];
 $Image=$importData['image'];
 $URlkey=$importData['url_key'];
  foreach ($categories as $catName) {
  $namePath .= (empty($namePath) ? '' : '/').strtolower($catName);
  if (empty($cache[$namePath])) {
  $dispMode = $this->_displayModes[2];
    $cat = Mage::getModel('catalog/category')
    ->setStoreId($store->getId())
    ->setPath($path)
    ->setName($catName)
    ->setIsActive($IsActive)
    ->setIsAnchor($IsAnchor)
    ->setDisplayMode($dispMode)->save();
   $cat = Mage::getModel('catalog/category')->load($cat->getId());
   $cat->setIncludeInMenu($IncludeInMenu);
   $cat->setDescription($Description);
   $cat->setMetaTitle($MetaTitle).
    $cat->setMetaKeywords($MetaKeywords);
    $cat->setMetaDescription($MetaDescription);
    $cat->save();
   $cat = Mage::getModel('catalog/category')->load($cat->getId());
   $data['meta_keywords']=$MetaKeywords;
   $data['meta_title']=$MetaTitle;
   $data['meta_keywords']=$MetaKeywords;
   $data['meta_description']=$MetaDescription;
   $data['url_key']= $URlkey;
   $cat->addData($data);
   $cat->save();
  $cache[$namePath] = $cat;
  }
  $catId = $cache[$namePath]->getId();
  $path .= '/'.$catId;
  $i++;
  }
  return true;
 }

 /**
 * Retrieve store object by code
 *
 * @param string $store
 * @return Mage_Core_Model_Store
 */
 public function getStoreByCode($store)
 {
  $this->_initStores();
  if (isset($this->_stores[$store])) {
  return $this->_stores[$store];
  }
  return false;
 }

 /**
 * Init stores
 *
 * @param none
 * @return void
 */
 protected function _initStores ()
 {
  if (is_null($this->_stores)) {
  $this->_stores = Mage::app()->getStores(true, true);
  foreach ($this->_stores as $code => $store) {
  $this->_storesIdCode[$store->getId()] = $code;
  }
  }
 }
}

?>

然后我继续在 app\etc\modules 创建 ImpCat_All.xml ImpCat_All.xml 看起来像这样,

<?xml version="1.0"?>
<config>
 <modules>
  <ImpCat_Catalog>
   <codePool>local</codePool>
   <active>true</active>
  </ImpCat_Catalog>
 </modules>
</config>

然后我在 admin > system >Import/Export > Dataflow - Advanced Profile 中创建了一个名为 category import 的数据流高级配置文件,并添加了这个 XML 代码。

<action type="dataflow/convert_adapter_io" method="load">
     <var name="type">file</var>
     <var name="path">var/import</var>
     <var name="filename"><![CDATA[Categories.csv]]></var>
     <var name="format"><![CDATA[csv]]></var>
    </action>
    <action type="dataflow/convert_parser_csv" method="parse">
     <var name="delimiter"><![CDATA[,]]></var>
     <var name="enclose"><![CDATA["]]></var>
     <var name="fieldnames">true</var>
     <var name="store"><![CDATA[0]]></var>
     <var name="number_of_records">1</var>
     <var name="decimal_separator"><![CDATA[.]]></var>
     <var name="adapter">catalog/convert_adapter_category</var>
     <var name="method">parse</var>
 </action>

【问题讨论】:

    标签: php magento-1.9 import-from-excel


    【解决方案1】:

    在一个接一个地尝试了数小时和数天之后,我终于想出了如何将我的所有类别导出和导入到新安装的 Magento 并保留所有原始 ID。

    从旧的 Magento 导出

    这是我的导出工具 exporter.php(通过浏览器或 CLI 运行),将此文件放在您的 Magento 根目录下。

    exporter.php

    <?php
    require_once 'app/Mage.php';
    Mage::app();
    $allCategories = Mage::getModel ( 'catalog/category' );
    $categoryTree = $allCategories->getTreeModel();
    $categoryTree->load();
    $categoryIds = $categoryTree->getCollection()->getAllIds();
    if ($categoryIds) {
      $outputFile = "var/export/categories-and-ids.csv";
      $write = fopen($outputFile, 'w');
      foreach ( $categoryIds as $categoryId ) {
        $parentId = $allCategories->load($categoryId)->getParentId();
        $data = array($parentId, $allCategories->load($categoryId)->getName(), $categoryId);
        fputcsv($write, $data);
      }
    }
    fclose($write);
    echo "File written at /var/export";
    ?>
    

    这会在/var/export/categories-and-ids.csv 处生成一个 CSV 文件 打开此文件并删除包含您的默认类别的第一行。您需要在安装中手动创建一个新的默认类别,记住它的 ID 并更正您的顶级类别父 ID。从 Export 得到的 CSV 文件的结构如下,

    1. 第一列是 Parent_Id
    2. 第二列是子类别的名称
    3. 第三列是旧商店的原始类别 ID

    我建议使用 OpenOffice Calc 来编辑和保存 CSV 文件。该文件必须是 UTF-8 格式,没有 BOM 格式。

    正在导入您的新商店

    要从您创建/编辑的 CSV 文件中导入您的类别,您只需从 Magento 根目录运行此导入器。 请记住编辑第 21 行以反映 CSV 的名称和位置。

    create-categories.php

    <?php
    /**
    * Script created by sonassi.com (http://www.sonassi.com/knowledge-base/quick-script-batch-create-magento-categories/)
    *
    * Edited by Christer Johansson for Magento 1.9.2.2 in december 2015
    *
    * File format of the CSV file categories-and-ids.csv :
    * parent_category_id,category_name,category_id
    * example: 3,subcat,5
    * -> This will create a subcategory with 'subcat' as name and 5 as category id. The parent category id is 3 (Can also be Root
    * Category with id 0).
    */
    
    define('MAGENTO', realpath(dirname(__FILE__)));
    require_once MAGENTO . '/app/Mage.php';
    
    setlocale(LC_ALL, 'en_US.UTF-8');
    umask(0);
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    
    $file = fopen('./var/import/categories-and-ids.csv', 'r');
    while (($column = fgetcsv($file)) !== FALSE) {
            //$column is an array of the csv elements
            if (!empty($column[0]) && !empty($column[1]) && !empty($column[2])) {
                    $data['general']['name'] = $column[1];
                    $data['general']['entity_id'] = $column[2];
                    $data['general']['meta_title'] = "";
                    $data['general']['meta_description'] = "";
                    $data['general']['is_active'] = 1;
                    $data['general']['url_key'] = "";
                    $data['general']['display_mode'] = "PRODUCTS";
                    $data['general']['is_anchor'] = 0;
    
                    $data['category']['parent'] = $column[0]; // 2 or 3 is top level depending on Magento version
                    $storeId = 0;
    
                    createCategory($data, $storeId);
                    sleep(0.5);
                    unset($data);
            }
    }
    
    function createCategory($data, $storeId) {
            echo "Starting {$data['general']['name']} [{$data['category']['parent']}] ...";
    
            $category = Mage::getModel('catalog/category');
            $category->setStoreId($storeId);
    
            if (is_array($data)) {
                    $category->addData($data['general']);
    
                    $parentId = $data['category']['parent'];
                    $parentCategory = Mage::getModel('catalog/category')->load($parentId);
                    $category->setPath($parentCategory->getPath() . "/" . $category->getId());
    
                    /**
                    * Check "Use Default Value" checkboxes values
                    */
                    if ($useDefaults = $data['use_default']) {
                            foreach ($useDefaults as $attributeCode) {
                                    $category->setData($attributeCode, null);
                            }
                    }
    
                    $category->setAttributeSetId($category->getDefaultAttributeSetId());
    
                    if (isset($data['category_products']) && !$category->getProductsReadonly()) {
                            $products = [];
                            parse_str($data['category_products'], $products);
                            $category->setPostedProducts($products);
                    }
    
                    try {
                            $category->save();
                            echo "Import successful - ID: " . $category->getId() . " - " . $category->getPath() . "<br /> ";
                    } catch (Exception $e){
                            echo "Failed import <br />";
                    }
            }
    
    }
    

    根据您的网站有多大以及您要导入多少类别,如果您有数千个类别,这将需要几秒钟到几分钟甚至几小时的时间。

    请耐心等待,该脚本将为您提供所有已导入类别的列表,并显示导入失败的类别。请记住在导入之前清理您的类别名称。

    导入完成后,清除缓存并通过管理员重新索引 Magento。在“管理类别”中查看您的类别,然后开始导入或创建产品。

    祝你好运! :)

    【讨论】:

    • 在您的导出脚本中,您关闭了一个您无法知道自己实际打开的文件。
    • 好吧,请随时更正我的代码。 :) 它在任何方面都不完美,但我成功地用它移动了 65000 多个产品和类别。
    • 我不是说你没有;我的意思是你不能关闭一个你没有打开的文件,这应该不言而喻,因为这是你的错误,也许这取决于你来纠正它。我还要补充一点,您应该在运行代码之前查看代码并仔细考虑。
    • 好的,但是文件打开和关闭。如果文件未打开,则脚本无法写入文件。我确实检查过。 :)
    • 我知道这已经很久了,但我想知道我是否可以使用这个脚本通过杀死他们的 ID 来导出客户、产品/类别和请求?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-14
    • 1970-01-01
    • 2012-11-12
    • 2017-04-06
    • 1970-01-01
    • 2014-10-17
    • 2011-09-08
    相关资源
    最近更新 更多