Magento – How to get Sku, name, and image in magento2 through programmatically

adminmagento-2.2.5productproduct-attribute

I don't know how to implement this task. I want to get product name, SKU, and image in magento2. Can you please help me?

Best Answer

I think you can fetch all product data using following code. Just put this code in your php file example.php. Hope it works.

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

require __DIR__ . '/app/bootstrap.php';
$params =  $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);

$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$mediaurl= $storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
$collection = $productCollection->create()
            ->addAttributeToSelect('*')
            ->load();

foreach ($collection as $product){
     echo 'Name  =  '.$product->getName().'<br>';
     echo 'Sku  =  '.$product->getSku().'<br><br>';
     $imagepath = $mediaurl.'catalog/product'.$product->getImage();
     $img = '<img src='.$imagepath.' />';
     echo $img;
}  

?>
Related Topic