0

I am using Magneto2.3.1 and i need to export all product sku and cateogry id in csv format runing custom script?if anyone know and idea share code please

2

You can use below script

<?php 

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$collection = $productCollection->addAttributeToSelect('sku','category_ids');

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="products.csv"');

$fp = fopen('php://output', 'wb');
fputcsv($fp, array("SKU","Category ID"));
foreach ($collection as $product){
    $sku = $product->getSku();
    $categoryIds = implode("-", $product->getCategoryIds());
    $val =array( $sku,$categoryIds);
    fputcsv($fp, $val);
} 
fclose($fp);

Hope this will help you!

1

Better we can use below code to get required attributes from collection instead of '*'

<?php 

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$collection = $productCollection->addAttributeToSelect('sku','category_ids');

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="products.csv"');

$fp = fopen('php://output', 'wb');
fputcsv($fp, array("SKU","Category ID"));
foreach ($collection as $product){
    $sku = $product->getSku();
    $categoryIds = implode(",", $product->getCategoryIds());
    $val =array( $sku,$categoryIds);
    fputcsv($fp, $val);
} 
fclose($fp);
  • Thanks for your reply:( – Rv Singh Nov 15 '19 at 5:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.