Magento – Get product collection in Magento2 root file

magento2

I need product collection In my root file so

How can I get the product collection in my root file in Magento2?

Best Answer

You can try the below code in your root file.

<?php

error_reporting(1);
ini_set('max_execution_time', 0);
use \Magento\Framework\App\Bootstrap;

require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$instance = \Magento\Framework\App\ObjectManager::getInstance();
$state = $objectManager->get('\Magento\Framework\App\State');
$state->setAreaCode('frontend');
$product_collections = $instance ->get('\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');
$collections = $product_collections->create();
foreach ($collections as $product) {
    print_r($product->getData());     
    echo "<br>";
}