Thursday 25 August 2011

Magento - Export Products with Full URLs

I needed to export a list of products with full URL links included. Normally you would just use the built in Import/Export functions, but these do not create the full URLs that I required.

This is what I came up with:
<?php

// Load the Magento core

require_once 'app/Mage.php';
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$userModel = Mage::getModel('admin/user');
$userModel->setUserId(0);

// Load the product collection

$collection = Mage::getModel('catalog/product')
 ->getCollection()
 ->addAttributeToSelect('*') //Select everything from the table
 ->addUrlRewrite(); //Generate nice URLs
/*
 For this example I am generating a CSV file,
 but you can change this to suit your needs.
*/

echo "title,sku,id,url\n";

foreach($collection as $product) {
 //Load the product categories
 $categories = $product->getCategoryIds();
 //Select the last category in the list
 $categoryId = end($categories);
 //Load that category
 $category = Mage::getModel('catalog/category')->load($categoryId);
 
 echo '"'.$product->getTitle().'","'.
  $product->getSku().'",'.
  $product->getId().',"'.
  //This will the proper URL, the base url is optional, though make sure you remove the trailing export.php (or whatever you name this file)
  str_replace('export.php/','',Mage::getBaseUrl()).$product->getUrlPath($category).'"'.
  "\n";
}


?>

Save it as export.php in your root Magento folder and browse to it in your browser.

3 comments:

  1. Thanks for this! Works great on an older version of Magento we have, but not a newer one we have running on php 5.3. Would that make a difference?

    Thanks again!
    BIll

    ReplyDelete
  2. Hi would you be available to offer a freelance job for me on this matter?
    please contact me at andy2000soft[at]gmail.com

    ReplyDelete
  3. it is not working in Magento CE 1.7.0.2

    ReplyDelete