Skip to content

Instantly share code, notes, and snippets.

@medigeek
Created January 28, 2021 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save medigeek/8cc6c02a40cbf8e5224ba6e6bd3b90b8 to your computer and use it in GitHub Desktop.
Save medigeek/8cc6c02a40cbf8e5224ba6e6bd3b90b8 to your computer and use it in GitHub Desktop.
Magento 2 script - export a product list (product name, sku and status)
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
function prepareCsv($csvData, $filename = "exportDataExample.csv", $delimiter = ',', $enclosure = '"'){
$f = fopen('php://memory', 'w');
$first = true;
foreach ($csvData as $line) {
/*if($first){
$titles = array();
foreach($line as $field => $val){
$titles[] = $field;
}
fputcsv($f, $titles, $delimiter, $enclosure);
$first = false;
}*/
fputcsv($f, $line, $delimiter, $enclosure);
}
fseek($f, 0);
header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
fpassthru($f);
}
try{
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$obj->get('Magento\Framework\Registry')->register('isSecureArea', true);
$appState = $obj->get('\Magento\Framework\App\State');
//$appState->setAreaCode('frontend');
$appState->setAreaCode('adminhtml'); //not required for terminal / php cli commands
/*$stores = $obj->get('\Magento\Store\Api\StoreRepositoryInterface')->getList();
foreach ($stores as $store) {
echo 'Store: ' . $store->getId() . ': '. $store->getName()."\n";
}
//exit();
*/
$products = $obj->create('\Magento\Catalog\Model\Product')->getCollection();
//->setStoreId(0);
$products
//->addAttributeToSelect('*')
->addAttributeToSelect(array('name','sku','status'))
//->addFieldTofilter('type_id','simple')
//->addFieldToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH)
//->addFieldToFilter('status', \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED)
->load();
//echo "Total products count: " . $products->count() . "<hr>";
//echo "<pre>";
if ($products->getSize() > 0) {
$arrayInfo = [];
foreach ($products as $product) {
//var_dump(get_class_methods($product));
//exit();
$arrayLine = [
$product->getName(),
$product->getSku(),
$product->getStatus()
];
$arrayInfo[] = $arrayLine;
//print_r($arrayLine);
//exit();
//print_r($product->getData());
}
}
prepareCsv($arrayInfo);
} catch (Exception $e) {
echo $e->getMessage();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment