Magento 2 export products csv programmatically

<?php
require './app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$_objectManager = $bootstrap->getObjectManager();
$state = $_objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');
$registry = $_objectManager->get('Magento\Framework\Registry');
$registry->register('isSecureArea', true);

//Store id of exported products, This is useful when we have multiple stores. 

$store_id = 1;
$outputFile = 'your/csv/path/allproexp.csv';
$fp = fopen($outputFile,"w+");
$heading = ['type','title','description','meta_keyword','seo_keywords','price','special_price','sku','simple sku'];

fputcsv($fp, $heading);

$collection = $_objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create()->addStoreFilter($store_id)->addAttributeToFilter('type_id', 'configurable')->addAttributeToSelect(array('name','sku','associated_skus','description','meta_keyword','seo_keywords','price','special_price'));

foreach ($collection as $product)

{

    $data = array();

    $data[] = $product->getTypeId();
    $data[] = $product->getName();
    $data[] = strip_tags($product->getDescription());
    $data[] = $product->getMetaKeyword();
    $data[] = $product->getSeoKeywords();
    $data[] = $product->getData('price');
    $data[] = $product->getData('special_price');
    $data[] = $product->getSku();

    $child_products = $product->getTypeInstance()->getUsedProducts($product, null);

    if(count($child_products) > 0)
    {
        $resultstr  = array();
        foreach($child_products as $child)
        {
            $resultstr[] = $child->getSku();
        }
        $data[] = implode(',', $resultstr);
    }  
  fputcsv($fp, $data);    
}
fclose($fp);
chmod('your/csv/path/allproexp.csv', 0777);
            if (file_exists($outputFile)) {
                //set appropriate headers
                header('Content-Description: File Transfer');
                header('Content-Type: application/csv');
                header('Content-Disposition: attachment; filename='.basename($outputFile));
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($outputFile));
                //ob_clean();flush();
                readfile($outputFile);
             } 

?>


Comments