Tuesday, February 14, 2017

Get product information programmatically in Magento 2

Get product information programmatically in Magento 2

<?php
use \Magento\Framework\App\Bootstrap;

#require __DIR__ . '/../app/bootstrap.php';
require '/www/mag2.local/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();

### Setting area code
### NOTE: for more info http://devdocs.magento.com/guides/v2.1/architecture/archi_perspectives/components/modules/mod_and_areas.html
$state = $objectManager->get('\Magento\Framework\App\State');
#$state->setAreaCode('base');

$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$storeId = $storeManager->getStore()->getId();

$productCollectionFactory = $objectManager->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$productCollection = $productCollectionFactory->create();
$productCollection->addAttributeToSelect('*');

foreach ($productCollection as $product) {
 echo 'Id: ' . $product->getId() . PHP_EOL;
 echo 'Sku: ' . $product->getSku() . PHP_EOL;
 echo 'Price: ' . $product->getPrice() . PHP_EOL;
 echo 'Weight: ' . $product->getWeight() . PHP_EOL;
 print_r($product->getData());
 echo PHP_EOL;
}

No comments: