答案 0 :(得分:1)
尝试此代码。
<?php
$mageFilename = 'app/Mage.php';
if (!file_exists($mageFilename)) {
echo $mageFilename." was not found";
exit;
}
require_once $mageFilename;
Mage::app();
try {
function getCategoryData()
{
$category = Mage::getModel('catalog/category');
$tree = $category->getTreeModel();
$tree->load();
$ids = $tree->getCollection()->getAllIds();
$categories = array();
$rootCategoryId = 2;
if ($ids)
{
foreach ($ids as $id)
{
$category->load($id);
$categories[$id]['name'] = $category->getName();
$categories[$id]['path'] = $category->getPath();
}
foreach ($ids as $id)
{
$path = explode('/', $categories[$id]['path']);
$string = '';
foreach ($path as $pathId)
{
if($pathId == 1 || $rootCategoryId == $pathId ) continue;
$string.= $categories[$pathId]['name'] . '/';
}
$categoryFullPaths[$id] = rtrim($string,"/");
}
}
return $categoryFullPaths;
}
function get_values_for_keys($mapping, $keys)
{
$output_arr = array();
foreach($keys as $key)
{
$output_arr[] = $mapping[$key];
}
return $output_arr;
}
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('category_ids');
$products->addAttributeToSelect('sku');
$fp = fopen('var/export/exports.csv', 'w');
$csvHeader = array("sku", "category_ids","category_name");
fputcsv( $fp, $csvHeader,",");
$cat_name = array();
$cat_array = array();
$categoryFullPaths = getCategoryData();
foreach ($products as $product)
{
$sku = $product->getSku();
$categoryIds = implode('/', $product->getCategoryIds());//change the category separator
$_cate_name = join(',', get_values_for_keys($categoryFullPaths, $product->getCategoryIds()));
fputcsv($fp, array($sku, $categoryIds,$_cate_name), ",");
}
fclose($fp);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}