我正在尝试调整此脚本,但没有办法工作。我按原样显示它,导入一个尊重层次结构的txt。我想做同样的事情,但只是使用数组,层次结构尊重数组键的值。
立即
demo.txt
水果(根类别)
苹果(类别)
我尝试做什么:
$ array = array (
'0 '=>' Fruits (Root category) ',
'1 '=>' Apples (category) ',
'2 '=>' Golden (subcategory) '
);
代码
<?php
// env config
ini_set('display_errors', 1);
umask(0);
// mage setup
require_once dirname(__FILE__).'/../app/Mage.php';
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
// open the tree file
if (!$handle = fopen("demo.txt", "r"))
die('Failed to open file');
// process tree
$last_offsets = 0;
$last_item_per_offset = array();
while (($line = fgets($handle)) !== false)
{
$offset = strlen(substr($line, 0, strpos($line,'-')));
$cat_name = trim(substr($line, $offset+1));
$category_collection = Mage::getModel('catalog/category')->getCollection()
->addFieldToFilter('name', $cat_name)
->setPageSize(1);
if (isset($last_item_per_offset[$offset-1]))
{
$category_collection->addAttributeToFilter('parent_id', (int)$last_item_per_offset[$offset-1]->getId());
}
if ($category_collection->count()) // item exists, move on to next tree item
{
$last_item_per_offset[$offset] = $category_collection->getFirstItem();
continue;
}
else
{
if ($offset-1 == 0 && !isset($last_item_per_offset[$offset-1])) // no root item found
{
echo "ERROR: root category not found. Please create the root\n";
}
else if(!isset($last_item_per_offset[$offset-1])) // no parent found. something must be wrong in the file
{
echo "ERROR: parent item does not exist. Please check your tree file\n";
}
$parentitem = $last_item_per_offset[$offset-1];
// create a new category item
$category = Mage::getModel('catalog/category');
$category->setStoreId(0);
$category->addData(array(
'name' => $cat_name,
'meta_title' => $cat_name,
'display_mode' => Mage_Catalog_Model_Category::DM_PRODUCT,
'is_active' => 1,
'is_anchor' => 1,
'path' => $parentitem->getPath(),
));
try {
$category->save();
} catch (Exception $e){
echo "ERROR: {$e->getMessage()}\n";
die();
}
$last_item_per_offset[$offset] = $category;
echo "> Created category '{$cat_name}'\n";
}
}
fclose($handle);
答案 0 :(得分:1)
您可以使用Magmi http://sourceforge.net/projects/magmi/。 节省了我很多时间。
答案 1 :(得分:0)
使用setData()
代替addData()
,需要添加parent category id
代码
$category->setData(array(
'name' => $cat_name,
'meta_title' => $cat_name,
'display_mode' => Mage_Catalog_Model_Category::DM_PRODUCT,
'is_active' => 1,
'is_anchor' => 1,
'path' => $parentitem->getPath(),
'parent_id' =>$parentCatId,
));
请告诉我,如果您有任何问题。