当前位置:  开发笔记 > 编程语言 > 正文

Magento中的CSV导入/导出问题

如何解决《Magento中的CSV导入/导出问题》经验,为你挑选了1个好方法。

好的,所以我设法通过遵循justcode.in上的一组指令将我的类别导出到csv文件中.我想将我的CSV导入到Magento的新安装中.

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

错误信息,


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

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.这个文件看起来像这样,



 
  
   
    
     ImpCat_Catalog_Model_Convert_Adapter_Category
    
   
  
 

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

Category.php看起来像这样,

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看起来像这样,



 
  
   local
   true
  
 

然后,我在管理>系统>导入/导出>数据流 - 称为类别导入的高级配置文件中创建了数据流高级配置文件,并添加了此XML代码.


     file
     var/import
     
     
    
    
     
     
     true
     
     1
     
     catalog/convert_adapter_category
     parse
 

Christer Joh.. 7

经过几个小时和几天尝试一个接一个的脚本后,我终于想出了如何将我的所有类别导出并导入到Magento的新安装并保留所有原始ID.

从您的旧Magento导出

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

exporter.php

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文件的结构如下,

    第一列是Parent_Id

    第二列是子类别的名称

    第三列是旧商店的原始类别ID

我建议使用OpenOffice Calc进行编辑和保存CSV文件.文件必须是UTF-8而没有BOM格式.

导入到您的新商店

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

创建-categories.php

 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() . "
"; } catch (Exception $e){ echo "Failed import
"; } } }

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

请耐心等待,脚本会为您提供所有导入类别的列表,并显示是否导入失败.请记住在导入前清除类别名称.

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

祝好运!:)



1> Christer Joh..:

经过几个小时和几天尝试一个接一个的脚本后,我终于想出了如何将我的所有类别导出并导入到Magento的新安装并保留所有原始ID.

从您的旧Magento导出

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

exporter.php

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文件的结构如下,

    第一列是Parent_Id

    第二列是子类别的名称

    第三列是旧商店的原始类别ID

我建议使用OpenOffice Calc进行编辑和保存CSV文件.文件必须是UTF-8而没有BOM格式.

导入到您的新商店

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

创建-categories.php

 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() . "
"; } catch (Exception $e){ echo "Failed import
"; } } }

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

请耐心等待,脚本会为您提供所有导入类别的列表,并显示是否导入失败.请记住在导入前清除类别名称.

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

祝好运!:)

推荐阅读
喜生-Da
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有