bluvertigo
8/7/2014 - 2:55 PM

Simple script to export a CSV from Magento for consumption by eKomi

Simple script to export a CSV from Magento for consumption by eKomi

<?php
require_once ("app/Mage.php");

class TradeOrders
{
    private static $headers = array('ORDER_ID', 'EMAIL', 'LAST_NAME', 'FIRST_NAME', 'PRODUCT_ID', 'PRODUCT_NAME');
    
    public static function get($from, $to) {
        
        // Fetch all UK Trade orders within specified date range
        Mage::app()->getStore()->setId(20);
        $orders = Mage::getModel('sales/order')
          ->getCollection()
          ->addAttributeToFilter('status', array('eq' => 'complete'))
          ->addAttributeToFilter('created_at', array('from' => $from, 'to' => $to,));
        
        // Prepare CSV file
        $f = fopen('/tmp/TradeOrders.csv', 'w+');
        fputcsv($f, self::$headers);
        foreach ($orders as $order) {
            $items = $order->getAllItems();
            
            // Build array of product SKUs within the order
            $skus = array();
            foreach ($items as $item) {
                $skus[] = $item->getSku();
            }
            
            // Remove duplicate SKU entries
            $skus = array_unique($skus);
            
            // Write record to CSV file
            foreach ($skus as $sku) {
		$data['order_id']     = $order->getId();
		$data['email']        = $order->getCustomerEmail();
		$data['last_name']    = $order->getCustomerLastname();
		$data['first_name']   = $order->getCustomerFirstname();
		$data['sku']          = $sku;
		$data['product_name'] = $item->getName();
                if ('dvnrth565@gmail.com' != $data['email']) {
                    fputcsv($f, $data);
                }
            }
        }
    }
}
$format = 'Y-m-d G:i:s';
$from   = date($format, strtotime('-90 days'));
$to     = date($format, strtotime('-4 hours'));
TradeOrders::get($from, $to);