Export Magento data to CSV format using custom PHP Code

Back to Blog
Ezeelive Technologies - Export Magento Database CSV Format Using Custom PHP Code

Export Magento data to CSV format using custom PHP Code

Export Magento data to CSV in PHP

Magento is one of the Best eCommerce platform in PHP using Zend Framework and Mage Class Library (Mage Static Classes). Magento is highly secure, dynamic SEO friendly, internationalization support, large number built-in features, and modular based system.

Magento System is growing day by day and it has a very good growing community, large no. of paid or free plugins, themes that anyone has in eCommerce Platforms. It has Core Code level access for a developer to see code class/functions and inbuilt module structure help for build/ develop custom plugins or modules for any eCommerce requirement.

Recently one of my Magento clients requires automatically database dump for products, categories, customers, and orders from the database to CSV and store datewise in one directory on the server for daily basis. For this, we have created PHP code and setup cronjob that runs in the early morning (4:00 AM IST) where website traffic has less traffic and server has less load.

After spending little time to Magento classes we found the very good solution for Export Magento Data to CSV,which we are sharing here :

Magento Products Export into CSV:

<?php
require_once 'app/Mage.php';
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app();
$fileHandle = fopen("product_dump_".date('Y-m-d').".csv", "w");
$productObj = Mage::getModel('catalog/product')->getCollection()->addAttributeToSelect('*'); // you can add * or field name here eg. ('sku','product_name','description')

foreach ($productObj as $productRow) {
    $dataCollection = array(
        $productRow->getSku(),
        $productRow->getName(),
        $productRow->getBrand(), // add attributes name here
        $productRow->getDescription(),
        $productRow->getUrlPath(),
        $productRow->getPrice(),
        $productRow->getFinalPrice()
    );
   fputcsv($fileHandle, $dataCollection);
}
fclose($fileHandle);

Export Magento Customers Data into CSV:

<?php
set_time_limit(0);
require_once ('app/Mage.php');
Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$resource = Mage::getSingleton('core/resource');
$read = $resource->getConnection('core_read');
$addressfields = getAttributes(2);
$fieldnames = getAttributes(1," AND attribute_code !='default_billing' AND attribute_code !='default_shipping'");
$fieldnames[] = 'current_server_entity_id';
$fieldnames[] = 'address';
$fieldsCount = count($fieldnames);
$fp = fopen('customers.csv', 'w');
fputcsv($fp, $fieldnames);
$customerCollection = Mage::getModel('customer/customer')
->getCollection()
->addAttributeToSelect('*'); // entity id from

foreach ($customerCollection as $customer) {
    $data = array();
    $addressData = array();
    foreach ($customer->getAddresses() as $address)
    {
       foreach ($addressfields as $field)
       {
          $data[$field] = $address->getData($field);
       }
       $data['default_billing'] =  ($customer->getDefaultBilling() == $address->getId());
       $data['default_shipping'] = ($customer->getDefaultShipping() == $address->getId());
       $addressData[] = $data;
    }
    $data = array();
    foreach ($fieldnames as $field)
    {
       $data[] = $customer->getData($field);
    }
    $data[$fieldsCount-2] = $customer->getId();
    //address data will be stored in the CSV which we can unserialize while exporting
    if (count($addressData) >0)
    {
       $data[$fieldsCount-1] = serialize($addressData);
    }
    fputcsv($fp, $data);
    echo '<br />CustomerId: ' . $customer->getId();
}
fclose($fp);
/**
* Get Attributes
* @param integer $typeId
* @param string $extraCondtion
* @return array $fieldnames
*/function getAttributes($typeId = 1,$extraCondtion='')
{
   $resource = Mage::getSingleton('core/resource');
   $read = $resource->getConnection('core_read');
   $query = 'SELECT attribute_code FROM eav_attribute WHERE entity_type_id = ' . $typeId;
   $query .= $extraCondtion;
   $attributes = $read->fetchAll($query);
   $fieldnames  = array();
   foreach ($attributes as $attribute)
   {
      $fieldnames[] = $attribute['attribute_code'];
   }
   return $fieldnames;
}
?>

Share this post

Comments (3)

  • MagikCommerce Reply

    This seems like a very short code for a very complex problem, but it seems to work flawlessly. Thanks for sharing.

    October 28, 2014 at 9:49 am
  • Priya Reply

    where to add the Customers Export into CSV:code in magento 2.2.5.Can you please reply to this mail

    August 16, 2018 at 4:10 pm
  • Priya Reply

    Can you please mention the file path of the code to add.

    August 16, 2018 at 4:11 pm

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Back to Blog