0

In a .phtml template file I have loaded a productCollection using objectManager as follow:

$productCollection = $objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Collection');
$values = [14];
$conditionType = "in";
$productCollection->addAttributeToSelect('*');
$productCollection->addCategoriesFilter([$conditionType => $values]);

I'd like to print a json with all the products, showing only the following product attributes:

  • Name
  • Sku
  • Link to img

What's the "Magento way" to do this? Thanks

1 Answer 1

1

Not sure if it's the correct/best way, but after some researches I got it working as follow:

$collection_to_encode = array();

// this is needed to get image URL
$imagehelper = $objectManager->create('Magento\Catalog\Helper\Image');


foreach( $productCollection as $product )
{
    $product_to_encode = array();

    $productsid = $product->getId();
    $productsname = $product->getName();
    $productsimageurl = $imagehelper->init($product, 'category_page_list')->getUrl();


    $product_to_encode[] = array(
        'id' => $productsid,
        'name' => $productsname,
        'image' => $productsimageurl );

    $collection_to_encode = array_merge($product_to_encode, $collection_to_encode);
}

$encoded_products = json_encode($collection_to_encode);

echo $encoded_products;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.