Magento 2 – Simple Export product to CSV

Posted on November 20, 2020 by jamie

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$objectManager = $bootstrap->getObjectManager();
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');


// Store id of exported products, This is useful when we have multiple stores. 
$store_id = 1;


$headers = ['Type', 'ID', 'Name', 'SKU'];

$fp = fopen("export.csv","w+");
    
    $productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
    $collection = $productCollectionFactory->create();
        // select attributes
        $collection->addAttributeToSelect(array('name','sku','id'));
         
        // filter current website products
        $collection->addWebsiteFilter();
         
        // filter current store products
        $collection->addStoreFilter();
         
        
        // fetching only 5 products
        $collection->setPageSize(5); 
        
        
        
    //put headers on csv
    fputcsv($fp, $headers);
    
    //loop collection
    foreach ($collection as $product) { 
        
        // echo $product->getTypeId() . '|'. $product->getId() . ' | '.$product->getSku(). ' | '.$product->getName() . PHP_EOL;
        
        $data = array();
            $data[] = $product->getTypeId();
            $data[] = $product->getId();
            $data[] = $product->getSku();
            $data[] = $product->getName();
        
            
    fputcsv($fp, $data);  
    }

fclose($fp);