自定义产品导出PHP脚本不起作用

时间:2018-09-26 09:53:14

标签: php csv customization magento-1.9 export-to-csv

我需要导出csv之类的SKU |类别编号|类别名称,导出后,SKU字段中的空白为空。

代码:https://codeshare.io/5Q690Q

如何查找错误?

1 个答案:

答案 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;
}