The example below shows how you can create a folder, retrieve data through external SFTP, analyze / import, then analyze / export and finally push data to external SFTP
Define a useful file / folder path, etc.
$baseDir = Mage::getBaseDir(); $varDir = $baseDir.DS.'var'; $timeOfImport = date('jmY_his'); $importReadyDir = $varDir.DS.'import_ready'.DS.$timeOfImport; $exportReadyDir = $varDir.DS.'export_ready'.DS.$timeOfImport; $_fileToImportRemote = '/home/skv/customers.txt'; $_fileToExportRemote = '/home/skv/customers_export.txt'; $_fileToImportBaseName = 'customers.txt'; $_fileToImportLocal = $importReadyDir.DS.'customers.txt'; $_fileToExportLocal = $exportReadyDir.DS.'customers_parsed.txt';
Then we will extract the file and save it until our magento installation.
$file = new Varien_Io_File(); //Create import_ready folder $importReadyDirResult = $file->mkdir($importReadyDir); if (!$importReadyDirResult) { //Handle error } $sftpPickupFile = new Varien_Io_Sftp(); try { $sftpPickupFile->open( array( 'host' => 'some.server.com', 'username' => 'skv', 'password' => 'MyPass', 'timeout' => '10' ) ); $_fileToImportRemoteTmp = $sftpPickupFile->read($_fileToImportRemote); if(!$_fileToImportRemoteTmp) { //Handle error } $sftpPickupFile->close(); if (!$file->write($_fileToImportLocal, $_fileToImportRemoteTmp)) { //Handle error } } catch (Exception $e) { //Handle error }
now this is an example of sending some data to a remote server
$flocal = new Varien_Io_File(); $flocal->open(array('path' => $importReadyDir)); $flocal->streamOpen('customers.txt', 'r'); while (false !== ($csvLine = $flocal->streamReadCsv())) { //Parse the data and import it... //Zend_Debug::dump($csvLine, '$csvLine'); /** $csvLine array(4) { [0] => string(13) "skv" [1] => string(16) " skv@email.com " [2] => string(2) "28" [3] => string(25) "Sample address for skv" } */ } //Now we do reverse, grab some data from Magento and upload it to SFTP $data = '"skv", " skv@email.com ", "28", "Sample address for skv" "skv", " skv@email.com ", "29", "Sample address for Tomas"'; $sftpDumpFile = new Varien_Io_Sftp(); try { $sftpDumpFile->open( array( 'host' => 'some.server.com', 'username' => 'skv', 'password' => 'MyPass', 'timeout' => '10' ) ); //Make a local backup that will be send to SFTP $file->mkdir($exportReadyDir); $file->write($_fileToExportLocal, $data); //Upload to SFTP $_fileToExportRemoteTmp = $sftpDumpFile->write($_fileToExportRemote, $data); } catch (Exception $e) { echo $e->getMessage(); }
source share