get product details in magento 2 code example
Example 1: magento2 get product collection
<?php
namespace Foungento\Theme\Block;
class Theme extends \Magento\Framework\View\Element\Template
{
protected $_productCollectionFactory;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
array $data = []
)
{
$this->_productCollectionFactory = $productCollectionFactory;
parent::__construct($context, $data);
}
public function getProductCollection()
{
$collection = $this->_productCollectionFactory->create();
$collection->addAttributeToSelect('*');
$collection->setPageSize(10);
return $collection;
}
}
?>
/*Display product collection in phtml file
Print out the product collection in phtml file with the below code:*/
list.phtml
$productCollection = $block->getProductCollection();
foreach ($productCollection as $product) {
print_r($product->getData());
echo "<br>";
}
Example 2: magento 1.9 get all product
$collection = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('*')
->setPageSize(5000)
->setCurPage(1);
foreach ($collection as $product) {
echo $product->getName();
echo (float) $product->getPrice();
echo $product->getDescription();
echo $product->getShortDescription();
echo $product->getTypeId();
echo $product->getStatus();
foreach ($product->getCategoryIds() as $category_id) {
$category = Mage::getModel('catalog/category')->load($category_id);
echo $category->getName();
echo $category->getParentCategory()->getName();
}
echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA).
'catalog/product'.$product->getImage();
echo $product->getSpecialPrice();
echo $product->getProductUrl();
echo '<br />';
}