Home » Php » php – Magento product export with full canonical url

php – Magento product export with full canonical url

Posted by: admin July 12, 2020 Leave a comment


Is there a way to get a list of products with their current canonical url on command line?

class Mage_Shell_UrlTest extends Mage_Shell_Abstract

public function run()
    $productCollection = Mage::getResourceModel('catalog/product_collection')
            ->setPageSize(10) // just for testing
            ->addAttributeToFilter('status', array(
                'eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED


    foreach ($productCollection as $product) {

        $url = $product->getUrlModel()->getUrl($product, array('_ignore_category' => true));

        echo PHP_EOL . $url . PHP_EOL; // debug output

$shell = new Mage_Shell_UrlTest();

I run it with php -f magento/shell/urlTest.php and this gives me something like this:


How to&Answers:

By default magento uses the same code to get the canonical url in Mage_Catalog_Block_Product_View::_prepareLayout() so the code should be fine. The only difference is for which store the code is executed.

It doesn’t work in shell scripts because they are executed for the admin store (see Mage_Shell_Abstract::__construct() where Mage::app() is initialized). You could use Mage::app()->setCurrentStore('default'); where you need to replace default by your store and the right urls should be printed.


I maybe do not understand properly what you mean by “canonical url” but if you mean the url of the product with its ID and the key at the end that is normally the “canonical url” for magento as it is supposed to be unique at a moment, you should just take away the params of the getUrl. If you do not want the key, you can still use :

$url = substr($url, 0, strrpos('/s/')); 

I hope it helps, if not, please precise the result you want.