Magento code export orders


After here, I will guide for you how to export orders with total products in there orders 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_orders.php

with content:


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


$collection = Mage::getResourceModel('sales/order_collection')
        'state', array(
            array('eq' => array('complete')),
            array('eq' => array('canceled')),
            array('eq' => array('closed'))
    ->setOrder('increment_id', 'DESC');

echo 'Total orders: '.count($collection)."<br/>";

//write to csv file
$currTime = date('Y-m-d_H-i-s', time());
try {
    //save file to server
    $fp = fopen('var/export/exports_orders_'.$currTime.'.csv', 'w');

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

    $csvHeader = array("Order #", "Email address", "Purchase quantity", "Date of purchase", "Status");
    fputcsv( $fp, $csvHeader,",");

    $i = $j = $k = 0;
    $arrId = array();
    foreach ($collection as $order) {
        $orderId        = $order->getIncrementId();
        $email          = $order->getCustomerEmail();
        $item_quantity  = ($order->getTotalQtyOrdered() * 1);
        $date_purchase  = $order->getCreatedAt();
        $status         = $order->getStatus();
        fputcsv($fp, array($orderId, $email, $item_quantity, $date_purchase, $status), ",");
        $j += $item_quantity;
catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "n";

echo 'Total products in orders: '.$j."<br/>";
echo 'Export success '.$i." orders.<br/><br/>";
echo "Export end.<br/>";


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

magento export orders

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_orders_'.$currTime.csv");
header("Pragma: no-cache");
$fp = fopen("php://output", "w");

and don’t forget comment this code:

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

Thanks for watching!