Magento 2 customer data in CSV using root script, or get customer data in a CSV file from MySQL
Create “myscript.php” file on Magento root or pub directory and add below code.
Execute this file from terminal like “php myscript.php“ or hit the URL like “example.com/myscript.php“
You can find the CSV file in pub/media/ folder.
use Magento\Framework\App\Bootstrap; use Magento\Framework\App\Filesystem\DirectoryList; require __DIR__ . '/../app/bootstrap.php'; $bootstrap = Bootstrap::create(BP, $_SERVER); $obj = $bootstrap->getObjectManager(); $obj->get('Magento\Framework\App\State')->setAreaCode('frontend'); $fileFactory = $obj->get('Magento\Framework\App\Response\Http\FileFactory'); $csvProcessor = $obj->get('Magento\Framework\File\Csv'); $directoryList = $obj->get('Magento\Framework\App\Filesystem\DirectoryList'); $content[] = [ 'email' => __('Email'), 'first_name' => __('First Name'), 'last_name' => __('Last Name'), 'phone_number' => __('Phone Number'), 'zipcode' => __('zip code'), 'counrty' => __('counrty'), ]; $fileName = 'customer_data.csv'; // Add Your CSV File name $filePath = $directoryList->getPath(DirectoryList::MEDIA) . "/" . $fileName; $countryFactory = $obj->get('Magento\Directory\Model\CountryFactory')->create(); $customerFactory = $obj->create('Magento\Customer\Model\CustomerFactory')->create(); $customerCollection = $customerFactory->getCollection()->addAttributeToSelect("*")->load(); foreach ($customerCollection as $customer) { //$address = $customer->getPrimaryBillingAddress(); $address = $customer->getPrimaryShippingAddress(); $telephone = ''; $postcode = ''; $countryName = ''; if($address){ $telephone = $address->getTelephone(); $postcode = $address->getPostcode(); $country_id = $address->getCountryId(); $country = $countryFactory->loadByCode($country_id); $countryName = $country->getName(); } $content[] = [ $customer->getEmail(), $customer->getFirstname(), $customer->getLastname(), $telephone, $postcode, $countryName ]; } $csvProcessor->setEnclosure('"')->setDelimiter(',')->saveData($filePath, $content); $storeManager = $obj->get('\Magento\Store\Model\StoreManagerInterface'); $url = $storeManager->getStore()->getBaseUrl(); echo '<a href="'.$url.'media/'.$fileName.'"> download </a>'; /*$fileFactory->create( $fileName, [ 'type' => "filename", 'value' => $fileName, 'rm' => false, // True => File will be remove from directory after download. ], DirectoryList::MEDIA, 'text/csv', null );*/
Like us on Facebook and Linkedin for more updates.
Related : How To Get Database Detail In Magento 2