Magento 2 Run Code From An External File/Script
To access the Magento 2 core functionality, we need to include the below code in the top of the external file
use Magento\Framework\App\Bootstrap;
require __DIR__ . ‘/app/bootstrap.php’;
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
Example file path: C:/xampp/htdocs/magento2/script.php
<?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’);
$quoteId = 1;
$quote = $obj->get(‘Magento\Checkout\Model\Session’)
->getQuote()
->load($quoteId);
echo ‘<pre>’;
print_r($quote->getOrigData());
echo ‘</pre>’;
$productId = 1;
$product = $obj->get(‘Magento\Catalog\Model\ProductRepository’)
->getById($productId);
echo ‘<pre>’;
print_r($product->getData());
echo ‘</pre>’;
?>