Magento code export products

magento

After here, I will guide for you how to export products with CSV format by code.

Simple, we need only create a PHP file in root directory magento and direct run with that file.

At here, I will create a file with name is: export_products.php

with content:

 

<?php
echo "Export products start...<br/>";
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;

Mage::app();
$products = Mage::getModel("catalog/product")->getCollection();
$products->addAttributeToSelect('entity_id');
$products->addAttributeToSelect('sku');
$products->addAttributeToSelect('name');
$products->setOrder('entity_id', 'DESC');

echo 'Total '.count($products)." products <br/><br/>";

//write to csv file
$currTime = date('Y-m-d_H-i-s', time());

try {
    //save file to server
    $fp = fopen('var/export/exports_products_'.$currTime.'.csv', 'w');

    //save file to local
    //header("Content-type: text/csv");
    //header("Content-Disposition: attachment; filename=exports_products_'.$currTime.csv");
    //header("Pragma: no-cache");
    //$fp = fopen("php://output", "w");

    $csvHeader = array("Id","Sku", "Name");
    fputcsv( $fp, $csvHeader,",");

    $i = $j = $k = 0;
    foreach ($products as $product) {
        $id     = $product->getId();
        $sku    = $product->getSku();
        $name   = $product->getName();
        fputcsv($fp, array($id, $sku, $name), ",");
        $i++;
    }
    fclose($fp);
} catch(Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "n";
}

echo 'Export success '.$i." items.<br/><br/>";

 

In above code, file export CSV will created at var/export/ and have name is exports_products with suffix is current date.

 

magento export products

 

If you want download that file after process export was finished, please uncomment this code:

header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=exports_products_'.$currTime.csv");
header("Pragma: no-cache");
$fp = fopen("php://output", "w");

and don’t forget comment this code:

//$fp = fopen('var/export/exports_products_'.$currTime.'.csv', 'w');

Thanks for watching!