Magento Code: Check an import directory for new product CSVs and process using a Magmi profile

Posted in Magento on 7 June 2017

This script will first scan the var/import directory for all CSV files starting “import-” using the glob() function in PHP. It will return an array of any files which match the query in the directory including the file path from root.

The $file_parts will be used later when we need just the file name.

$cmd is the executable shell command we will be using to load Magmi, set the profile, mode and chosen file.

The shell_exec() function runs the command and will return any output to the $output variable, this can be expanded to check for a successful import. The script below will carry on regardless of import status.

Once the import is complete we take the CSV and copy it into an archive folder, just in case we want to reuse it. The original file is then deleted from the var/import folder using unlink()

This script can then either be run manually, or set-up as a scheduled task using Cron.

// Find all CSV files in import directory
$files = glob('/home/admin/public_html/var/import/import*.csv');

// For each of the files found 
foreach ($files as $file):

   // Explode for teh the file name in 6th position of the array
   $file_parts = explode("/",$file);

   // Set-up the command 
   $cmd = 'php /home/admin/public_html/magmi/cli/magmi.cli.php -profile=default -mode=create -CSV:filename="'.$file.'"';

   // Execute the comamnd 
   $output = shell_exec($cmd);

   // Copy the executed script into an archive folder
   if ( copy($file,'/home/admin/public_html/var/import/archive/'.$file_parts[6]) ):
      // Delete the original
      unlink($file);
   endif;

endforeach;

Related Magento Posts

January 2024

Using Magento to get small businesses online

For small businesses aiming to establish a formidable online presence and drive sales, Magento emerges as a powerful e-commerce platform offering a suite of features... Continue reading

October 2023

Magento database structure

The database structure of Magento is designed to store and manage various aspects of an e-commerce website, including products, orders, customers, and more. Understanding the... Continue reading

August 2023

Accessibility in ecommerce websites

In the digital age, where online shopping has become an integral part of our lives, ecommerce websites hold the key to business success. Amidst the... Continue reading

More Magento Posts